简体   繁体   English

如何随机选择对象键?

[英]How can I choose an object key at random?

I have the following code; 我有以下代码;

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? 我怎样才能做到这一点?

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

If you are capable of using libraries, you may find that Lo-Dash JS library has lots of very useful methods for such cases. 如果您能够使用库,您可能会发现Lo-Dash JS库对于这种情况有很多非常有用的方法。 In this case, go ahead and check sample(). 在这种情况下,请继续检查sample()。

(Note Lo-Dash convention is naming the library object _. Don't forget to check installation in the same page to set it up for your project.) (注意Lo-Dash约定是命名库对象_。不要忘记在同一页面中检查安装以为项目设置它。)

_.sample([1, 2, 3, 4]);
// → 2

In you case, go ahead and use: 在你的情况下,继续使用:

_.sample(namedarray)

and in context: 并在上下文中:

document.getElementById('question').innerHTML="Q." +_.sample(namedarray)+"  is capital for which country";

On a side note, you could use a simpler notation for populating the array. 另外,您可以使用更简单的表示法来填充数组。

namedarray = {
    India : 'New Delhi',
    Australia : 'Canberra',
    Indonasia : 'Jakarta',
    Iran : 'Tehrani',
    Iraq : 'Bhagdad',
    Nijeria : 'Abuja'
}

I would just use two arrays for the data. 我只想使用两个数组作为数据。

var countries = ['India', 'Australia', 'Indonasia', ... ];
var capitols = ['New Delhi', 'Canberra', 'Jakarta', ...];

Then insert into your text with: 然后插入到您的文本中:

var index = Math.floor(Math.random() * capitols.length);
document.getElementById('question').innerHTML="Q." +capitols[index]+"  is capital for which country";

You can then use the index variable to look up the answer later on as well. 然后,您可以使用index变量稍后查找答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM