-1


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?

Vignesh Raja
  • 7,927
  • 1
  • 33
  • 42
uhbc
  • 84
  • 1
  • 8

3 Answers3

2

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • @nina, Out of the context, isn't it should be `random(a,b)` inside `random2` method, assuming the OP need to create `min` number of random numbers between `min` and `max` values ? Even the OP is wrong in his implementation. – Vignesh Raja Nov 16 '18 at 13:40
  • @VigneshRaja, please ask op. – Nina Scholz Nov 16 '18 at 13:42
1

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.

Vignesh Raja
  • 7,927
  • 1
  • 33
  • 42
0

Set the length to zero

x.length = 0;
Josef Fazekas
  • 447
  • 5
  • 11