【问题标题】:Why an empty array of N length in javascript does not have indices?为什么javascript中长度为N的空数组没有索引?
【发布时间】:2021-12-30 04:36:18
【问题描述】:

所以我在 Javascript 中创建了一个空数组

const x = Array(5);

或者

const x = new Array(5);

如果我检查长度,在这两种情况下都是5,但是当我使用.map 循环它时,它没有给我索引,即0,1,2,3,4

x.map((el, i) => i);

这应该返回[0,1,2,3,4]

【问题讨论】:

标签: javascript arrays


【解决方案1】:

因为the specification requires,当使用 Array 构造函数创建数组时,其中values 是参数列表:

a. Let len be values[0].
b. Let array be ! ArrayCreate(0, proto).
c. If Type(len) is not Number, then
  i. Perform ! CreateDataPropertyOrThrow(array, "0", len).
  ii. Let intLen be 1?.
d. Else,
  i. Let intLen be ! ToUint32(len).
  ii. If SameValueZero(intLen, len) is false, throw a RangeError exception.
e. Perform ! Set(array, "length", intLen, true).
f. Return array.

仅此而已,仅此而已。简而言之,它创建一个继承自Array.prototype 的新数组对象,然后在其上设置length 属性。它不会在数组上创建任何数字索引。

好像

const createArray = (length) => {
  const newArr = Object.create(Array.prototype);
  newArr.length = length;
  return newArr;
};

const arr = createArray(5);
console.log(arr.length);
console.log(arr.hasOwnProperty('0'));

因此,如果您想遍历数组,您必须先以某种方式填充它 - 使用 .fillArray.fromspreading it into a new array.

【讨论】:

  • 感谢您的详细回答,这真的很有帮助。你能解释一下这在哪里有用吗?我的意思是实际用例?
  • 我想,在极少数情况下,人们想创建一个具有给定大长度的数组,而不用同时用值填充所有这些索引。但这真的很奇怪。最好的做法是在所有情况下都避免使用稀疏数组。我认为,如果今天重新设计该语言,就会重新审视这种行为——它造成的混乱远比它提供的好处多。
猜你喜欢
  • 2013-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多