Reputation: 1099
After initialing an array, it contains empty elements. I want to set an element back to empty after setting an value. But it doesn't work however I set it to undefined/null.
var a = Array(20181231);
// it will not run.
a.forEach(e => {console.log(++i + ' - ' + e);});
var i = 0;
a[12] = 12;
a[2018] = 2018;
// it loop twice
a.forEach(e => {console.log(++i + ' - ' + e);});
a[12] = undefined;
// expecting one time, but it still loop twice.
a.forEach(e => {console.log(++i + ' - ' + e);});
Upvotes: 2
Views: 291
Reputation: 386512
You could take the delete
operator and remove the element of the array.
var a = Array(20181231);
a.forEach(e => console.log(++i + ' - ' + e)); // no loop
var i = 0;
a[12] = 12;
a[2018] = 2018;
a.forEach(e => console.log(++i + ' - ' + e)); // two elements
delete a[12];
a.forEach(e => console.log(++i + ' - ' + e)); // one element
Upvotes: 4