How can I choose an object key at random?

后端 未结 3 584
余生分开走
余生分开走 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:43

    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.

提交回复
热议问题