简体   繁体   中英

wait for while loop to end before executing code

I am trying to retrieve data from an object, I generate 3 random numbers from 1-9 and then pick out data from a json object using these random numbers. However it sometimes works and then sometimes doesn't, I think it might be because it doesn't wait for the random numbers to be generated before selecting data from the object, it all occurs on page load:

the jsfiddle: http://jsfiddle.net/dbqw79j4/1/

the code:

var jsonfile =[      
        {
        "id" : "article1",
        "image" : "http://images.domain.com/is/image/boss/BOSS_london_bridge_skyline?$c_overview_large$",
        "headline" : "<h2>EIN TAG IN LONDON<span class='h2'>MIT LEWIS HAMILTON</span></h2>"
        },
        {
        "id" : "article2",
        "image" : "http://images.domain.com/is/image/boss/FAB_5819?$c_overview_large$",
       "headline" : "<h2>EIN TAG IN MONACO<span class='h2'>MIT NICO ROSBERG</span></h2>"
        },
  ...
]

var arr = []
var article1;
var article2;
var article3;

var art1hd;
var art1img;

var art2hd;
var art2img;

var art3hd;
var art3img;


while(arr.length < 3){
  var randomnumber=Math.ceil(Math.random()*9)
  var found=false;
  for(var i=0;i<arr.length;i++){
    if(arr[i]==randomnumber){found=true;break}
  }
  if(!found)arr[arr.length]=randomnumber;
}
console.log(arr);
console.log(arr[0]);
console.log(arr[1]);
console.log(arr[2]);


article1 = arr[0];
article2 = arr[1];
article3 = arr[2];

console.log(article1)
console.log(article2)
console.log(article3)


art1hd = jsonfile[article1]['headline'];
art1img = jsonfile[article1]['image'];

art2hd = jsonfile[article2]['headline'];
art2img = jsonfile[article2]['image'];

art3hd = jsonfile[article3]['headline'];
art3img = jsonfile[article3]['image'];

console.log(art1hd)
console.log(art1img)

console.log(art2hd)
console.log(art2img)

console.log(art3hd)
console.log(art3img)

You generate random numbers from range of 0-9 and your array contains only 9 elements and it is indexed from 0-8

You should use:

while(arr.length < 3){
  var randomnumber=Math.ceil(Math.random()*8)
  var found=false;
  for(var i=0;i<arr.length;i++){
    if(arr[i]==randomnumber){found=true;break}
  }
  if(!found)arr[arr.length]=randomnumber;
}

The problem is, your "jsonfile" array has nine elements. this breaks when you generate the random number 9, as arrays are zero-based, the valid values for indexing the array are 0-8

Math.ceil() is never the right function to generate an integer result based on Math.random() times something as this code does:

var randomnumber = Math.ceil( Math.random() * 9 );

You should always use Math.floor() in code like this instead. If you don't want your range to start with 0, then add the range base after doing the Math.floor() .

In other words, if you want a random integer in the range 1 through 9 inclusive, this is the correct way to do it:

var randomnumber = Math.floor( Math.random() * 9 ) + 1;

Why is this? It's important to understand that Math.random() produces a value that is greater than or equal to 0, and less than (but never equal to) 1.

So Math.random() * 9 gives a value that is always less than 9 (and never equal to 9). If you take Math.floor() on that, you now have an integer in the range 0 through 8 inclusive.

Add 1 to that, and you have your desired range of 1 through 9.

Many JavaScript references fail to describe Math.random() clearly. Just keep in mind that its result is in the range 0 <= Math.random() < 1 .

So, what could go wrong if you used Math.ceil() ? Going back to the original example:

var randomnumber = Math.ceil( Math.random() * 9 );

What this code actually does is generates a number in the range 0 through 9, not 1 through 9. Now the chance of getting a 0 result is extremely small: it would be fairly rare for Math.random() to return 0, but it can happen . By using Math.floor() instead, you insure that the result is always in the desired range.

That said, as suvroc points out, you're (eventually) using this value as an index into an array of 9 elements, therefore the range you want is actually 0 through 8. So the code should be:

var randomnumber = Math.floor( Math.random() * 9 );

这是因为随机数生成器可以生成数字9,但是您的jsonfile只有9个元素,所以最后一个索引是8。

First, as others said the random number generated as to be :

Math.floor(Math.random()*9)

Then I reviewed the code to be sure of synchronicity : http://jsfiddle.net/dbqw79j4/6/

I did a recursive function who calls logs on arr.length >= 3 and add a random number if it doesn't exists on arr.

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