Array.from 在 Array#map 中不能用作直接回调函数
Array.from doesn't work as a direct callback function in Array#map
我从Array.from
发现了一些非常奇怪的行为。当映射到类似数组的对象数组时,它似乎不能直接用作回调函数。我已经在Chrome中进行了测试。
下面是一些测试代码 (ES6):
const fails = () => {
const x = {
0: 'help',
length: 1
};
const y = [x].map(Array.from); // will throw an Error
return y;
};
const works = () => {
const x = {
0: 'help',
length: 1
};
const y = [x].map(item => Array.from(item)); // will work
return y;
};
console.log(works());
console.log(fails());
https://jsfiddle.net/dox6wnya/
这是非常奇特的行为。我想知道为什么会这样。
.map
将三个参数传递给它的回调(currentValue
,index
,array
),.from
接受三个参数(arrayLike
,mapFn
,thisArg
)。参数类型不匹配和/或产生意外结果;特别是"0 is not a function
",其中0
是传递给mapFn
的index
参数。唯一真正兼容的参数是第一个,这就是为什么它是你应该通过的唯一参数。
相关文章:
- JavaScript回调函数
- 如何在回调函数中执行流
- 回调函数中传递参数的困难(Google Map API Markers)
- 如何正确地将参数传递给RequireJS回调函数
- 回调函数在python代码中离线
- 从AJAX回调函数中分离数据
- 赋值后的回调函数
- 如何在javascript回调函数中返回多个变量
- 函数表达式,返回回调函数
- 等待回调函数执行
- JavaScript回调函数和Google Feed API
- 如何从ajax成功回调函数中读取javascript变量
- 正在保存JavaScript内部回调函数中的值
- 有没有什么方法可以停止Jquery中的animate(也可以停止完整的回调函数)
- 如何在javascript中添加带有回调函数的按钮点击事件作为window.conf
- 在Golang回调函数中启用CORS
- 在初始函数完成之前调用回调函数
- jQuery Mobile:如何在$.Mobile.changePage之前运行回调函数
- 即使使用回调函数也无法返回值
- 为什么prototypjs观察到回调函数有绑定