2

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

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.