[英]wait for while loop to end before executing code
我试图从一个对象检索数据,我从1-9生成3个随机数,然后使用这些随机数从json对象中选取数据。 但是有时它起作用,有时却不起作用,我认为这可能是因为它不等待从对象中选择数据之前就生成随机数,而这一切都是在页面加载时发生的:
jsfiddle: http : //jsfiddle.net/dbqw79j4/1/
编码:
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)
您从0-9范围内生成随机数,并且数组仅包含9个元素,并且从0-8进行索引
您应该使用:
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;
}
问题是,您的“ jsonfile”数组具有九个元素。 这会在您生成随机数9时中断,因为数组是从零开始的,因此索引数组的有效值为0-8
Math.ceil()
永远不是正确的函数,无法根据Math.random()
乘以以下代码来生成整数结果:
var randomnumber = Math.ceil( Math.random() * 9 );
您应该始终在这样的代码中使用Math.floor()
。 如果您不希望范围以0开头,则在执行Math.floor()
之后添加范围基础。
换句话说,如果您想要一个介于1到9之间的随机整数,这是正确的方法:
var randomnumber = Math.floor( Math.random() * 9 ) + 1;
为什么是这样? 重要的是要了解Math.random()
产生一个大于或等于 0且小于(但永远不等于)1的值。
因此Math.random() * 9
给出的值始终小于9(并且永远不等于9)。 如果对此使用Math.floor()
,则现在将有一个介于0到8(含)之间的整数。
加上1,则您需要的范围是1到9。
许多JavaScript参考都无法清楚地描述Math.random()
。 请记住,其结果在0 <= Math.random() < 1
的范围内。
因此,如果您使用Math.ceil()
,可能会出错吗? 回到原始示例:
var randomnumber = Math.ceil( Math.random() * 9 );
该代码实际执行的操作是生成一个介于0到9之间的数字,而不是1到9。现在得到0结果的机会非常小: Math.random()
返回0的情况很少,但是可能发生 。 通过使用Math.floor()
代替,可以确保结果始终在所需范围内。
就是说,正如suvroc指出的那样,您(最终)将使用此值作为9个元素的数组的索引,因此,所需的范围实际上是0到8。因此代码应为:
var randomnumber = Math.floor( Math.random() * 9 );
这是因为随机数生成器可以生成数字9,但是您的jsonfile
只有9个元素,所以最后一个索引是8。
首先,正如其他人所说,随机数生成为:
Math.floor(Math.random()*9)
然后,我检查了代码以确保同步性: http : //jsfiddle.net/dbqw79j4/6/
我做了一个递归函数,它调用arr.length >= 3
上的日志,如果arr不存在则添加一个随机数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.