javascript - 这段创建连续数字数组的代码是如何工作的?

标签 javascript arrays

我在网上找到了这段代码并且它有效;但是,我不知道如何!

谁能解释一下这段代码是如何工作的吗?

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/

相关文章:

javascript - 为什么我的程序无论用户输入如何总是打印第一个条件?

arrays - 如何检查空数组(结构数组)

javascript - 动态且高效地将今天的日期作为字符串分配给属性

javascript - 动态添加到 Jquery && Asp.net 应用程序中的列表

java - 将父对象转换为子对象 - 数组中的奇怪行为

java - 如何使用Servlet在MySQL中保存数组?

php - 如何在不检查每个值(如果存在)的情况下防止重复记录

javascript - 我可以记录鼠标移动吗?

javascript - JS 将未定义值转为空字符串

javascript - XMLHTTPRequest 发送数据