使用序列号在Javascript中映射数组 [英] Mapping Array in Javascript with sequential numbers

查看:67
本文介绍了使用序列号在Javascript中映射数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码:

let myArray = Array.apply(null, {length: 10}).map(Number.call, Number);

创建以下数组:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

我只是不明白为什么。我无法在互联网上找到解释此行为的任何内容。有谁知道为什么这样做的方式呢?也许是某些文档的链接?

I just don't understand why. I can't find anything on the internet that explains this behavior. Does anyone know why this works the way it does? Perhaps a link to some documentation?

推荐答案

Array.apply(null, {length: 10})

创建一个长度为10的数组,所有元素都是 undefined

creates an array of length 10 with all elements being undefined.

.map(Number.call, Number)

将为参数的每个元素调用 Number.call (元素,索引,数组)并将设置为数字。调用的第一个参数将被视为 this (这里不相关),所有其他参数都按原样传递,第一个参数是索引。而Number现在将其第一个参数 index 转换为一个数字(这里:将返回索引,因为它是一个数字),这就是地图将写入的数字返回数组。

will invoke Number.call for each element with the arguments (element, index, array) and setting this to Number. The first argument to call will be taken as this (not relevant here), and all the other arguments are passed as they are, with the first one being the index. And Number will now convert its first argument, index, to a number (here: will return the index, as it is a number), and that's what map will write to its return array.

这篇关于使用序列号在Javascript中映射数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆