本文介绍了如何随机选择对象键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码;

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";

我想代替尼泊尔,从对象中随机选择一个钥匙.我该怎么办?

In place of Nepal, I want to choose a key from the object at random. How can I do this?

推荐答案

尝试一下:

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"

这篇关于如何随机选择对象键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 14:20