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);});
1 Answer 1
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
answered Dec 31, 2018 at 12:52
Nina Scholz
388k26 gold badges367 silver badges417 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js