简体   繁体   中英

How does delete exactly work?

Please check the jsfiddle - http://jsfiddle.net/du8svaym/

var a = [2, 4, "bang", undefined, NaN, 5];

for (i in a)
alert(a[i]); //alerting a[3]=undefined

delete a[1];
for (i in a)
alert(a[i]); //Why not alerting a[1]= undefined?

alert(a[1]); //it is undefined! but not alerted, what is happening under the hood?

If you notice, the first loop alert alerts a value which is undefined. In the 2nd loop alert a[1] is undefined since we deleted it, but is not alerted. What is the difference between the two undefined, how exactly or differently is delete setting the undefined?

The delete operator removes a property from an object. Arrays are JavaScript objects like so:

var foo = {
  '0': 2,
  '1': 4,
  '2': "bang",
  '3': undefined, 
  '4': NaN,
  '5': 5
}
delete foo[1]; // completely removes the property '1' from foo.
console.log(foo);
// outputs:
{
  '0': 2,
  '2': "bang",
  '3': undefined, 
  '4': NaN,
  '5': 5
}

For the first iteration, the array looks like this.

[0: 2, 1: 4, 2: "bang", 3: undefined, 4: NaN, 5: 5]

Now, after you delete a 1 , it removes 4. So, now the array looks like

[0: 2, 2: "bang", 3: undefined, 4: NaN, 5: 5]

Now, as you can see a 1 does not exist. So it gives undefined.

Deleting an element will not affect the array length, as it does not change the indexes. If you want the array index to be affected, use splice .

JavaScript Arrays are sparse, that means that they do not have to store a value at every position. Delete removes the value at the position, making it sparse.

Try this

a = []; // empty array
a[1000] = 'hello';
for (i in a) {
    console.log(i);
}
console.log(a.length)

You will see that it will only print 1000 in the loop whereas the length of the array is 1001

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