delete array[i]
和array[i] = undefined
一样吗?我知道前者会产生稀疏数组。后者是否也会产生相同的结果?
delete array[i]
和array[i] = undefined
一样吗?我知道前者会产生稀疏数组。后者是否也会产生相同的结果?
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
});
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 withdelete
.
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 thedelete
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 }
通过同时使用两者,可以使密集数组变得稀疏或不稀疏。它们的用法是不同的。
让我们看看...
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