将数组Javascript

时间:2018-12-31 12:48:31

标签: javascript arrays

初始化数组后,它包含空元素。我想在设置值后将元素设置回空。但这不起作用,但是我将其设置为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 个答案:

答案 0 :(得分:4)

您可以使用delete operator并删除数组的元素。

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