在我的浏览器控制台中,我输入了以下内容:
Array.forEach.apply(null,['a','b','c'])
回应是:
Uncaught TypeError: b is not a function at String.forEach (<anonymous>) at <anonymous>
我不太确定我认为会发生什么,但事实并非如此。也:
Array.prototype.forEach.apply(null,['a','b','c']);
Uncaught TypeError: Array.prototype.forEach called on null or undefined at forEach (<anonymous>) at <anonymous>
我觉得理解这有助于扩展我的JS智慧。任何圣人JS开发人员都知道这个吗?
此外:
['a','b','c'].forEach.apply((function(a,b){return b;}),['a','b','c'])
回应是:
Uncaught TypeError: a is not a function at String.forEach (<anonymous>) at <anonymous>
答案 0 :(得分:-1)
问题在于,当您要传递要运行的null
数组时,您将.forEach()
作为第一个参数传递给 .apply()
。
然后, .forEach()
要求为它提供一个将为每个数组项调用的回调函数,而.apply()
方法要求您传递任何其他参数一个数组也是如此。典型的.forEach()
调用如下所示:
[...].forEach(function(value, index, array) { ...callback code...});
因此整个函数参数也需要提供给.apply()
。
.apply()
应该传递(thisArg, [ arg, arg, arg, ...])
,第二个参数是要应用的函数所需的参数数组。
因此,这里是您所看到的内容,原因和正确语法的细分:
// The following fails with an error of: "Cannot read property 'apply' of undefined"
// because .forEach is a member of Array.prototype
//Array.forEach.apply(null,['a','b','c'])
// The following fails with an error of: "Array.prototype.forEach called on null or undefined"
// because .forEach is being passed null when it should be passed the array that it needs
// to enumerate:
//Array.prototype.forEach.apply(null,['a','b','c'])
// Pass the array to enumerate and an array of any arguments that .forEach() requires:
Array.prototype.forEach.apply(['a','b','c'], [ function(v,i,a){ console.log(v); } ]);