gpt4 book ai didi

javascript - Array.from 不能作为 Array#map 中的直接回调函数

转载 作者:行者123 更新时间:2023-11-28 15:10:08 30 4
gpt4 key购买 nike

我从 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三个参数传递给其回调(currentValueindexarray),.from 接受三个参数(arrayLikemapFnthisArg)。参数类型不匹配和/或产生意外结果;特别是“0 不是函数”,其中 0 是传递给 mapFnindex 参数。唯一真正兼容的参数是第一个,这就是为什么它是您唯一应该传递的参数。

关于javascript - Array.from 不能作为 Array#map 中的直接回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36834176/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com