首页 > 解决方案 > 删除数组中的所有元素 - 函数在数组末尾附加“未定义”

问题描述


这是我的代码

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也会添加到数组中。
我该如何预防?

标签: javascriptarrayspushsplice

解决方案


您不需要执行返回的函数调用,undefined而只需调用函数random2,因为函数本身会将元素添加到数组中。

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

var x = [];

random2(5, 100);
console.log(x);

x.length = 0;          // better performance than x.splice(0, x.length)
random2(5,100);        // call without using push
console.log(x);        // no undefined anymore

更好的方法是在 中返回一个数组random2,因为此函数不访问外部定义的数组。要推送值,您可以采用扩展语法。

function random(min, max) {
    return Math.floor(Math.random() * (min - max)) + min;
}

function random2(a, b) {
    return Array.from({ length: a }, _ => random(0, b));
}

var x = random2(5, 100);
console.log(x);

x.length = 0;          
x.push(...random2(5, 100));
console.log(x);


推荐阅读