我在网上找到了这段代码并且它有效;但是,我不知道如何!
谁能解释一下这段代码是如何工作的吗?
const arr_seq = Array.apply(null, {
length: 10
}).map(Number.call, Number);
console.log(arr_seq)
输出是:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
另外,谁能解释一下为什么这段代码(我认为它可能会做完全相同的事情)却创建了一个充满 undefined
的数组?
const arr_undef = Array(n).map(Number.call, Number);
最佳答案
Array.apply
期望其第二个参数为数组(类似)值。然后,它将为这个类似数组的对象中的每个槽创建一个参数。
由于此代码通过 { length: 5 }
作为参数,apply
方法将调用Array
有 5 个值。但是当阅读{ length: 5 }[i]
时对于 i
在 0..4 范围内,它总是会得到 undefined
。所以Array.apply(null, { length: 5 })
将翻译为Array(undefined, undefined, undefined, undefined, undefined)
.
然后是.map
call 有第二个参数,即 thisArg
争论。这确保了不仅仅是 call
被调用,但是 Number.call
,即右 this
环境。与Number.call
第一个参数将接收那些 undefined
值(在上一段中进行了解释)和作为第二个参数的映射索引。所以我们接到这些电话:
Number.call(undefined, 0)
Number.call(undefined, 1)
Number.call(undefined, 2)
Number.call(undefined, 3)
Number.call(undefined, 4)
这给出了相同的结果:
Number(0)
Number(1)
Number(2)
Number(3)
Number(4)
和.map
将返回包含这些值的数组。
执行此操作的新方法
自 ECMAScript 2015 以来,JavaScript 已 Array.keys()
和数组文字的扩展语法。所以我们现在可以用一种不太神秘的方式实现同样的目的:
console.log([...Array(5).keys()]);
关于javascript - 这段创建连续数字数组的代码是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72981202/