JavaScript数组地图应用 [英] javascript Array map with apply

查看:108
本文介绍了JavaScript数组地图应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想申报和0初始化数组中的JavaScript。我创建了一个数组,并设置长度是这样的。

I am trying to declare and initialize an array with 0, in javascript. I created an array and set the length like this.

var previousRow = [];
previousRow.length = 5;

然后,我这样做。

Then, I did this.

console.log(previousRow);
previousRow = previousRow.map(Number.prototype.valueOf, 0);
console.log(previousRow);

和我,

[ , , , ,  ]
[ , , , ,  ]

但是,当我做了

console.log(previousRow);
previousRow = Array.apply(null, previousRow).map(Number.prototype.valueOf, 0);
console.log(previousRow);

我得到了我的预期。

I got what I expected

[ , , , ,  ]
[ 0, 0, 0, 0, 0 ]

为什么第一个code没有工作?

Why the first code didn't work?

推荐答案

阅读MDN文档<一个href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map\"><$c$c>map.它明确规定:

Read the MDN documentation for map. It clearly states:

回调仅针对已赋值数组的索引引用;它不为其调用已被删除或没有被赋于值指标。

callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.

previousRow 数组是空数组长度 5 。然而元素从未被分配一个值:

The previousRow array is an empty array of length 5. However the elements have never been assigned a value:

var previousRow = [];
previousRow.length = 5;

由于元素 previousRow 还没有被赋于他们将永远不会被处理的值的地图 。因此映射 Number.prototype.valueOf previousRow 将会导致5个元素的空数组:

Since the elements of previousRow have never been assigned a value they will never be processed by map. Hence mapping Number.prototype.valueOf over previousRow will result in an empty array of 5 elements:

console.log(previousRow);
previousRow = previousRow.map(Number.prototype.valueOf, 0);
console.log(previousRow);

然而,当你适用 previousRow 阵列构造函数构造函数创建一个新的阵列和 previousRow 的值分配给新的数组。

However when you apply previousRow to the Array constructor the constructor creates a new array and assigns the values of previousRow to the new array.

没关系 previousRow 的元素是否赋值。当JavaScript不能找到一个值它提供未定义代替。

It doesn't matter whether the elements of previousRow were assigned a value. When JavaScript can't find a value it supplies undefined instead.

因此​​,最终的结果是,新的数组有5个元素所有这一切都是分配 未定义通过明确的阵列构造函数。因此,你可以使用地图来处理整个数组:

Hence the net effect is that the new array has 5 elements all of which are assigned undefined explicitly by the Array constructor. Hence you can use map to process the entire array:

console.log(previousRow);
previousRow = Array.apply(null, previousRow).map(Number.prototype.valueOf, 0);
console.log(previousRow);

您应该阅读更深入的解释如下回答: http://stackoverflow.com/a/18949651/783743

You should read the following answer for a more in depth explanation: http://stackoverflow.com/a/18949651/783743

这篇关于JavaScript数组地图应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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