我无法理解以下代码的工作原理。当我尝试打印 v
的值时,我得到的 undefined
时间与 length
一样多。
Array.from({length: 5}, (v, i) => i);
// [0, 1, 2, 3, 4]
尝试过的代码:
console.log(Array.from({length: 3}, function(v,i) {
console.log(v);
console.log(i);
return i;
}));
最佳答案
引用docs :
Array.from()
has an optional parametermapFn
, which allows you to execute a map function on each element of the array (or subclass object) that is being created.More clearly,
Array.from(obj, mapFn, thisArg)
has the same result asArray.from(obj).map(mapFn, thisArg)
, except that it does not create an intermediate array.
现在,让我们分别检查每个部分。 Array.from({length: 5})
计算结果为...
[undefined, undefined, undefined, undefined, undefined]
standard中有详细解释。简而言之,结果是一个具有相同 length
值的常规数组,每个连续元素(从 0
到 length-1
)设置为某个值 - 要么从参数对象中获取,要么从参数对象中获取,或者如果没有(例如在您的情况下),则为“未定义”。
现在, map 函数如下所示:
(v, i) => i
...忽略(它所使用的数组的值)并仅返回索引,每个元素一个。因此,映射转换本质上是创建一个数组,其中每个元素都等于其索引 - [0, 1, 2, ...]
。
关于javascript - 从包含 length 属性的对象创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49919490/