【问题标题】:javascript: Why can some functions be bound and mapped and others not?javascript: 为什么有些函数可以绑定和映射,而有些则不能?
【发布时间】:2015-07-21 20:36:07
【问题描述】:

出于好奇:

MDN 教我如何使用这样的快捷功能应用:

trim = Function.prototype.call.bind(String.prototype.trim)

join = Function.prototype.call.bind(Array.prototype.join)

现在,我可以映射trim,但由于某种原因不能映射joinjoin',' 作为默认参数(分隔符),所以我应该没问题,但它使用数组索引:

> trim = Function.prototype.call.bind(String.prototype.trim)
call()
> [' a','b '].map(trim)
["a", "b"]
> join = Function.prototype.call.bind(Array.prototype.join)
call()
> [['a','b'],['c','d']].map(join)
["a0b", "c1d"]

为什么?

另外,如果我真的想要一个不同的分隔符怎么办?将它传递给bind 不起作用,因为它被附加到现有参数(在任何时候我映射到的列表的元素之一)之前。然后它扮演要连接的字符串的角色,如果有要分隔的东西,要连接的字符串将充当分隔符:

> joins = Function.prototype.call.bind(Array.prototype.join,';')
call()
> [['a','b'],['c','d']].map(joins)
[";", ";"]

我研究发现:

Answers explaining the thing with this and solutions equivalent to the bind shortcut I referenced

Similar explanations, the solution using thisArg again, from MDN's page about map

A duplicate question with duplicate answers

【问题讨论】:

标签: javascript


【解决方案1】:

您传递给 map 的函数接收 3 个参数。基本上地图是这样工作的。

Array.prototype.map = function(f) {
  var result = [];
  for(var i = 0; i < this.length; i++) {
    result.push(f(this[i], i, this));
  }
  return result;
}

所以当你运行这段代码时 [['a','b'],['c','d']].map(join), 这就是map内部发生的事情

join(['a', 'b'], 0, [['a','b'],['c','d']])
join(['c', 'd'], 1, [['a','b'],['c','d']])

要获得您想要的结果,您可以编写一个可以生成连接函数的函数。例如

function joinSep(separator) {
  return function(array) {
    return array.join(separator)
  }
}
var joins = joinSep(';');
[['a','b'],['c','d']].map(joins)

【讨论】:

    猜你喜欢
    • 2020-07-25
    • 2017-01-27
    • 2014-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-17
    • 1970-01-01
    • 2013-04-23
    相关资源
    最近更新 更多