简体   繁体   中英

Delete all elements in an array - Function appends 'undefined' at the array end


Here is my code

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 ]

I simply wanna remove all the elements in the array then add new elements in it. But when I try to do it with the code above, undefined is also adding to the array.
How can I prevent it?

You need not to puish the function call, which returns undefined , but just call the function random2 , because the function itselft add the elements to the array.

 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 

A better approach is to return an array in random2 , because this function does not access an outer defined array. To push the values, you could take the spread syntax.

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

To empty an array, there are multiple ways as explained here with some benchmark results and explanation regarding their performance.

As an aggregation, asssume 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()){}

You have called the function random2 inside the push method. So random2 method first inserts the values in the array x and returns the default value undefined ( Reference ), which in turn gets pushed into the array. Hence the value.

将长度设置为零

x.length = 0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM