简体   繁体   中英

array.splice vs setting a value to null

You should use array.splice(i, 1); instead of array[i] = null This will preserve the keys in the array

Source : Should I bother cleaning array in node.js?

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); will remove the element from array, so changing the length of array.

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 .

Regarding

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

Why array[i] = null will not change the keys(or rather length ) of the array?

Second question:

Why array.splice(i, 1); is better?

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.

It's fairly easy to see the differences in behaviour with a simple test case. This is what Chrome outputs from the console:

var test = ['a','b','c']
test[1] = null
["a", null, "c"]

var test = ['a','b','c']
test.splice(1, 1)
["a", "c"]

var test = ['a','b','c']
delete test[1]
["a", undefined × 1, "c"]

As you can see, splice is the only one to change the index of c from 2 to 1.

Which one you want to use depends on your use case. There may be a case where you have a fixed-length array, and you want to remove an item without affecting the index of items after it, in which case splicing would be inappropriate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM