我有以下代码;
namedarray['India']='New Delhi';
namedarray['Australia']='Canberra';
namedarray['Indonasia']='Jakarta';
namedarray['Iran']='Tehrani';
namedarray['Iraq']='Bhagdad';
namedarray['Nijeria']='Abuja';
document.getElementById('question').innerHTML="Q." +namedarray['Nepal']+" is capital for which country";
我想代替尼泊尔,从对象中随机选择一个钥匙。我怎样才能做到这一点?
最佳答案
尝试这个:
function fetch_random(obj) {
var temp_key, keys = [];
for(temp_key in obj) {
if(obj.hasOwnProperty(temp_key)) {
keys.push(temp_key);
}
}
return obj[keys[Math.floor(Math.random() * keys.length)]];
}
var random_name = fetch_random(namedarray);
document.getElementById('question').innerHTML="Q." + random_name +" is capital for which country"