samedi 9 avril 2016

How to generate a random key in ES5? [duplicate]

This question already has an answer here:

I have a function that normally returns the "first" key but I want one that will return a purely random key:

// return any key
// note this will not always be the first key
Pub.oneKey = function (obj) {
    var key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) {
            return key;
        }
    }
    return false;
};

I am aware of Math.random

http://ift.tt/1tVWgkS

but it looks like you will have to setup a numerical relationship to the key using

Object.keys()

some how.




Aucun commentaire:

Enregistrer un commentaire