方法Array.splice VS设定值设置为null [英] array.splice vs setting a value to null
问题描述
您应该使用方法Array.splice(I,1);
而不是数组[我] = NULL
此将preserve阵列中的键
You should use
array.splice(i, 1);
instead ofarray[i] = null
This will preserve the keys in the array
Source : Should I bother cleaning array in node.js?
我真的不理解这句话。为什么数组[我] = NULL
将改变阵的钥匙?为什么方法Array.splice(1,1);
更好
I don't really understand this sentence. Why array[i] = null
will change the keys of the array ? Why array.splice(i, 1);
is better ?
推荐答案
方法Array.splice(I,1);
从数组中删除的元素,所以改变了长度
阵。
array.splice(i, 1);
will remove the element from array, so changing the length
of array.
而数组[我] = NULL
将只指数 I
的值设置为无效
并不会改变数组的长度。这是一样的删除阵列[我]
除了删除
运营商将在索引处的值设置为未定义
。
Whereas array[i] = null
will just set the value at the index i
to null
and will not alter the array length. This is same as delete array[i]
except the delete
operator will set the value at the index to undefined
.
关于
为什么数组[我] = NULL
将改变阵的钥匙?
Why
array[i] = null
will change the keys of the array?
我觉得在意志和变化之间缺少一个字的不的
I think there is missing a word not in between the will and change.
因此,根据对我来说,它应该是
So, according to me, it should be
为什么数组[我] = NULL
将不可以更改密钥(或相当的长度的)的数组?
Why
array[i] = null
will not change the keys(or rather length) of the array?
第二个问题:
为什么方法Array.splice(1,1);
更好
这从它删除元素改变了数组的长度
。所以,遍历数组时,你不必检查如果(价值== NULL)
。
It alters the length
of the array by removing the element from it. So, when iterating over array you don't have to check if(value == null)
.
要完全使用哪一个取决于所使用的情况。
Which one to use totally depends on the use-case.
这篇关于方法Array.splice VS设定值设置为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!