(new Array(10))。map(function(){return 1;})返回[,,,,, ...]为什么? [英] (new Array(10)).map(function() { return 1;}) returns [, , , , , ...] ... Why?

查看:466
本文介绍了(new Array(10))。map(function(){return 1;})返回[,,,,, ...]为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望以下代码返回 [1,1,1,1 ...]

(new Array(10)).map(function() { return 1;})

但它返回 [,,,,, ...]

此外,
(新数组(10))。长度== 10 (新数组(10))[0] == undefined 为真。

对于 z = function(){return 0;}; 表达式 z(未定义)=== 0 也是如此。

然而我注意到了 [,,,,,,,,,,] .map(function(){return 1;})也返回 [,,,,。 ...]

Yet I have noticed that [,,,,,,,,,,].map(function() { return 1; }) also returns [,,,,....].

任何人都可以解释原因吗?

Can anyone explain why?

推荐答案


所以。我希望以下代码返回[1,1,1,1 ...]。

So. I would expect the following code to return [1,1,1,1...].

(new Array(10))。 map(function(){return 1;})
但它返回[,,,,, ...]。

(new Array(10)).map(function() { return 1;}) But it returns [, , , , , ...].

是的,因为 new Array(10)创建一个无元素长度 10, map 仅迭代实际存在的元素。 (是的,这 令人惊讶。:-))

Right, because new Array(10) creates an array with no elements with a length of 10, and map only iterates over elements that actually exist. (And yes, this is surprising. :-) )


此外,( new Array(10))。length == 10 (new Array(10))[0] == undefined true

再次更正,因为(再次) new Array( 10)没有在数组中放置任何元素,因此访问 [0] 会给你 undefined

Again correct, because (again) new Array(10) doesn't put any elements in the array, so accessing [0] gives you undefined.

JavaScript的标准数组根本不是真正的数组,并且它们的长度 这是一个正数而没有任何条目。它们是稀疏数组的一种形式。

JavaScript's standard arrays aren't really arrays at all, and they can have a length that's a positive number without having any entries in them. They're a form of "sparse" array.

让我们举一个更简单的例子:

Let's take a simpler example:

var a = new Array(10);
a[2] = 1;

该数组包含一个元素,索引元素 2 。索引 0 中没有元素,索引 1 中没有元素,索引中没有元素 3 及以上。它只是有差距。您可以通过询问来判断:

That array contains one element, the element at index 2. There is no element at index 0, no element at index 1, and no elements at indexes 3 and above. It just has gaps there. You can tell by asking it:

console.log(0 in a); // "false"
console.log(1 in a); // "false"
console.log(2 in a); // "true"

JavaScript中的标准数组只是具有指定给<$ c $的特殊行为的对象c> length ,分配给一类属性名称的特殊行为(松散地,数字名称),并由 Array.prototype 支持。

Standard arrays in JavaScript are just objects with special behavior assigned to length, special behavior assigned to a class of property names (loosely, numeric ones), and that are backed by Array.prototype.

这与新的类型数组相反, Int32Array 等等,这些都是真正的数组。传统意义。

This is all in contrast to the newer "typed" arrays, Int32Array and such, which are true arrays in the traditional sense.

这篇关于(new Array(10))。map(function(){return 1;})返回[,,,,, ...]为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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