0

enter image description herewhat I want is to create an array with random numbers so I can then add them to another array with a foreach

let jsonlength = this.accesoriosJson.length
let a = 0;
let randomNumber = new Array()
var myInterval = setInterval(function(){
  a++
  if (a > jsonlength) {
    clearInterval(myInterval);
  }else{
     randomNumber.push(Math.ceil(Math.random()*10))
  }
},100)

console.log(randomNumber) 

randomNumber.forEach(valor => {console.log(valor)}) 

I don't understand why the foreach doesn't work because console.log(randomNumber) works just fine

2
  • Why do you use a delay to push the nunbers? (where you wait 100 ms) Commented Aug 24, 2020 at 7:19
  • Are you sure console.log(randomNumber) works fine? Commented Aug 24, 2020 at 7:19

2 Answers 2

4

When the forEach call happens, randomNumber doesn't have any entries in it, so forEach doesn't do anything. You're only adding entries later, when the setInterval callback runs. That happens long after (in computer terms) your forEach call.

Sign up to request clarification or add additional context in comments.

Comments

1

I think for your purpose you should do something like this.

Call getRandomArray() after clearInterval(myInterval) to get RandomArray.

let jsonlength = 6;
let a = 0;
let randomNumber = new Array()
var myInterval = setInterval(function() {
  a++
  if (a > jsonlength) {
    clearInterval(myInterval);
    getRandomArray();
  } else {
    randomNumber.push(Math.ceil(Math.random() * 10))
  }
}, 0);

function getRandomArray() {
  console.log(randomNumber);

  randomNumber.forEach(valor => {
    console.log(valor)
  })
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.