samedi 22 juin 2019

How to get a random key

If I have the following:

var liststuff = {'key 1':'value 1', 'key 2':'value 2', 'key 3':'value 3'};

How should I go around to get a random key?

So the idea is that I would run a function and it will randomly give me one of the keys from liststuff, which I then could use to do what I want.

I though about giving 2 keys to each value, where the first one would be the 'key n', while the second key would be 'n-1' (n = number of keys):

e.g.

var belonging = {'Tom':'fish', 0:'fish', 'Jerry':'cheese', 1:'cheese', 'Billy':'pencil', 2:'pencil'};

And then I could do the following to get the random key:

let randChoice = Math.floor(3 * Math.random);
belonging[randChoice];

But then it would take too much space as the number of keys increases, and was wondering if there is a different and smarter way of doing this.




Aucun commentaire:

Enregistrer un commentaire