"array[i]=undefined"是否会产生一个稀疏数组?

3

delete array[i]array[i] = undefined一样吗?我知道前者会产生稀疏数组。后者是否也会产生相同的结果?

3个回答

3
不,后者并不是做同样的事情,它只是将该索引设置为值undefined,而不是删除该索引。delete会删除该索引,但不会更新长度,所以最终你得到一个索引真正未定义的数组,而不仅仅是包含值undefined的数组。
换句话说,这是一个“稀疏”数组,其中长度大于项目数。
你可以使用大多数数组方法轻松地测试它们,因为它们将迭代值undefined,但不会迭代未定义的索引(有区别)

var arr = [0, 1, 2, 3];

delete arr[1]; // delete the second index

arr.forEach(function(item) {
  console.log(item); // 0, 2, 3
});

console.log('--------')

var arr2 = [0, 1, 2, 3];

arr2[1] = undefined; // set the second index to "undefined"

arr2.forEach(function(item) {
  console.log(item); // 0, undefined, 2, 3
});


1
不,它们并不相同。来自MDN的 delete 运算符文章

Deleting array elements

When you delete an array element, the array length is not affected. This holds even if you delete the last element of the array.

When the delete operator removes an array element, that element is no longer in the array. In the following example, trees[3] is removed with delete.

var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
delete trees[3];
if (3 in trees) {
  // this does not get executed
}

If you want an array element to exist but have an undefined value, use the undefined value instead of the delete operator. In the following example, trees[3] is assigned the value undefined, but the array element still exists:

var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
trees[3] = undefined;
if (3 in trees) {
  // this gets executed
}

0

通过同时使用两者,可以使密集数组变得稀疏或不稀疏。它们的用法是不同的。

让我们看看...

var arr = [1,2,3];
delete arr[10]; // <- returns true but arr is not sparse
delete arr[1];  // <- returns true and arr is now sparse

var arr = [1,2,3];
arr[1]  = undefined; // <- arr is not sparse
arr[10] = undefined; // <- arr is now sparse

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接