【发布时间】:2019-04-19 16:32:54
【问题描述】:
这是我的代码
var x = [];
function random(min,max) {
return Math.floor(Math.random() * (min-max))+min;
}
function random2(a, b) {
for (let i = 0; i < a; i++) {
x.push(random(0,b));
}
}
random2(5, 100);
console.log(x); // [ -43, -27, -38, -21, -79 ]
x.splice(0, x.length);
x.push(random2(5,100));
console.log(x); // [ -24, -97, -99, -43, -66, undefined ]
我只是想删除数组中的所有元素,然后在其中添加新元素。
但是当我尝试使用上面的代码时,undefined 也在添加到数组中。
如何预防?
【问题讨论】:
-
为什么不用
x = []重置它? -
那么,
x = [];而不是拼接什么的呢? -
或
x.length = 0; -
你为什么不给它分配一个空数组呢? 'x=[]'
标签: javascript arrays push splice