How can I choose an object key at random?

后端 未结 3 583
余生分开走
余生分开走 2021-01-15 23:14

I have the following code;

namedarray[\'India\']=\'New Delhi\';
namedarray[\'Australia\']=\'Canberra\';
namedarray[\'Indonasia\']=\'Jakarta\';
namedarray[\'I         


        
3条回答
  •  孤街浪徒
    2021-01-15 23:24

    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"
    

提交回复
热议问题