Array forEach pass "push"作为参数
Array forEach pass "push" as argument
面对JS中的奇怪问题。我收到这个错误:
let a = []
let b = [1,2,3]
b.forEach(a.push)
TypeError: Array.prototype.push called on null or undefined
at Array.forEach (native)
at repl:1:3
at REPLServer.defaultEval (repl.js:262:27)
at bound (domain.js:287:14)
at REPLServer.runBound [as eval] (domain.js:300:12)
at REPLServer.<anonymous> (repl.js:431:12)
at emitOne (events.js:82:20)
at REPLServer.emit (events.js:169:7)
at REPLServer.Interface._onLine (readline.js:211:10)
at REPLServer.Interface._line (readline.js:550:8)
当然,我已经提出了一个建议,上下文丢失了。所以,我试着用这种方式来完成:
b.forEach([].push.bind(a))
结果变得不可预测:
[ 1, 0, [ 1, 2, 3 ], 2, 1, [ 1, 2, 3 ], 3, 2, [ 1, 2, 3 ] ]
什么?0是从哪里来的?好吧,也许是"故障"指数,但为什么不先比?:)
说明一下,这是以经典的方式工作的,这不是一个问题:
b.forEach(el => a.push(el) )
有人能解释一下这种奇怪的行为吗? 基本上按照forEach
的标准语法,它有3个不同的参数,current item
, index
和array
,在这些参数上调用forEach。因此,与a
绑定的push
函数每次都会调用这些参数。这就是问题所在。
iteration 1 : a.push(1,0,[1,2,3]) //since a was bound with push
iteration 2 : a.push(2,1,[1,2,3])
iteration 3 : a.push(3,2,[1,2,3])
你的代码将像上面那样执行
因为.forEach()
为你的回调提供了3个参数
回调有三个参数:
- 元素值
- 元素索引
- 正在遍历的数组
.push()
可以接受任意数量的参数。因此,在每次迭代中,.push()
将这三个参数添加到数组中。
相关文章:
- $.Ajax投掷“;无效的参数"在IE9上
- 我怎么能读“;.on()"jQuery中的方法参数
- jQuery脚本,它搜索现有的查询参数并且不添加“"如果存在
- AngularJS'ng:areq错误参数"{controller}不是函数“;,CodeIgnite
- "这个“;当我向事件处理程序函数添加参数时会发生更改
- 有没有一种方法可以在javascript中停止气泡而不使用"e”;参数
- 我怎么能在一个URL中有两种类型的参数,其中一种以“”开头#"而另一个以“0”开头&"并且不替
- MongoDb聚合$match错误:"参数必须是聚合管道运算符“;
- "这个“;在参数函数中
- 为什么使用"空”;以测试是否传递了参数
- "无效的参数"在IE 8上的jQuery.prepend()中
- Rails/javascript:"参数键太多”-什么'这是规范表单数据的好方法
- Javascript setInterval()-为什么我的"输入“;参数更改为未定义
- 如何发送类似“<>"在参数中使用$.ajax-to-server
- "这个“;当函数作为链中的参数传递时未定义
- "假的“;类构造函数中的参数
- "缺少)后参数列表”;错误--Can't Find A Bug
- “=>"在array.map()的参数中使用时
- jQuery AJAX和IE8输出“;无效的参数"
- Angular JS&TypeScript-错误:ng:areq错误参数"自变量'XXXXXX