【问题标题】:Delete all elements in an array - Function appends 'undefined' at the array end删除数组中的所有元素 - 函数在数组末尾附加“未定义”
【发布时间】: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


【解决方案1】:

您不需要执行返回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);

【讨论】:

  • @nina,断章取意,是不是应该在random2方法中使用random(a,b),假设OP需要在min和@之间创建min个随机数987654330@ 值?甚至 OP 在他的实施中也是错误的。
  • @VigneshRaja,请询问操作。
【解决方案2】:

要清空数组,有多种方法,如 here 所述,其中包含一些基准测试结果和有关其性能的说明。

作为一个聚合,假设var a = [1,2,3,4,5]

  1. a = []
  2. a.length = 0
  3. a.splice(0, a.length)
  4. a = new Array()
  5. while(a.pop()){}
  6. while(a.shift()){}

您在 push 方法中调用了函数random2。所以random2 方法首先将值插入数组x 并返回默认值undefined (Reference),然后将其推入数组。因此价值。

【讨论】:

  • 谢谢。没错,起初无法意识到这一点,但感谢 Nina,帮助我意识到这一点。
  • 很高兴你得到它。 :)
  • @uhbc 断章取意,是不是应该是random(a,b)random2方法里面,假设你需要在minmax之间创建min个随机数价值观?
【解决方案3】:

将长度设置为零

x.length = 0;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 2018-04-08
    • 2012-12-02
    • 2015-04-17
    • 2017-06-29
    • 1970-01-01
    • 2021-10-22
    相关资源
    最近更新 更多