阅读 the answers to this question我知道 delete
为元素设置了 undefined
值。
因此,如果我们有一个数组:a = [1, 2, 3]
(至少)在客户端使用 delete a[1]
数组将变为 [1, undefined x 1, 3]
这是真的,在客户端。
NodeJS 中发生了什么?
但是在 NodeJS(服务器端)上测试相同的操作我得到以下结果:
$ node
> a = [1, 2, 3]
[ 1, 2, 3 ]
> delete a[1]
true
> a
[ 1, , 3 ]
> a[1] = undefined
undefined
> a
[ 1, undefined, 3 ]
>
因此,a[1] = undefined
设置了未定义的值。但是两个逗号 ([1, , 3]
) 之间的空格是什么意思? 删除
放上去!为什么?
我猜空格的意思是undefined
,但是为什么它没有显示为undefined
只有我把它设置为undefined?
为什么会这样?
最佳答案
当您在数组条目上使用 delete
时,它会从数组中删除该条目。数组长度没有改变,但数组中的那个槽消失了。如果您尝试查看该插槽的值,它将显示为 undefined
,但删除它与将其设置为 undefined
并不完全相同。您可以阅读有关删除数组条目的信息 here (向下滚动到副标题“删除数组元素”)。
该引用还解释了在数组条目上使用 delete
与将其设置为 undefined
之间的区别。差异很细微,仅在少数情况下有所不同。这是该文章中的示例:
// using delete
var trees = ["redwood","bay","cedar","oak","maple"];
delete trees[3];
if (3 in trees) {
// this does not get executed
}
// setting to undefined
var trees = ["redwood","bay","cedar","oak","maple"];
trees[3]=undefined;
if (3 in trees) {
// this gets executed
}
所以,这个控制台输出:
[ 1, , 3 ]
向您显示第二个数组条目丢失(完全消失)。
查看本文 http://perfectionkills.com/understanding-delete/详细了解 delete
运算符在其他情况下的工作方式。
关于javascript - 在数组中的 NodeJS 中删除真正意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19207154/