How can I choose an object key at random?

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

    If you are capable of using libraries, you may find that Lo-Dash JS library has lots of very useful methods for such cases. In this case, go ahead and check 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.)

    _.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'
    }
    

提交回复
热议问题