I was wondering whether there is an easy way to select a random object from an array where one of the objects attributes matches a variable.
Something like this:
var ninjas = [
{ name: "Sanji Wu", affiliation: "good" },
{ name: "Chian Xi", affiliation: "good" },
{ name: "Chansi Xian", affiliation: "bad" },
{ name: "Chin Chu", affiliation: "bad" },
{ name: "Shinobi San", affiliation: "neutral" },
{ name: "Guisan Hui", affiliation: "neutral" }
];
function getRandom(attr) {
var r = Math.floor(Math.random() * ninjas.length);
//pseudo code below
if (this affiliation is "attr") {
return a random one that matches
}
// end pseudo code
};
var randomItem = getRandom("good");
Aucun commentaire:
Enregistrer un commentaire