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);});

asked Dec 31, 2018 at 12:48

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

answered Dec 31, 2018 at 12:52
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.