Array.from 在 Array#map 中不能用作直接回调函数

Array.from doesn't work as a direct callback function in Array#map

本文关键字:回调 函数 不能 from Array#map Array      更新时间:2023-09-26

我从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 is not a function",其中0是传递给mapFnindex参数。唯一真正兼容的参数是第一个,这就是为什么它是你应该通过的唯一参数。