I am trying to get a random element within an array, inside an object. I want to reuse that random element for another property in an object. The problem is the function is trying to generate a random number again every time I call that. For example, the object.randomWord()
will return a different result than the object.wordSplit()
. How to make sure all properties reference the same random element? Thanks.
var object = {
wordArray: ["falconheavy", "roadster", "tesla","openai"],
randomWord: function () {
return this.wordArray[Math.floor(Math.random()*this.wordArray.length)];
},
wordSplit: function () {
return this.randomWord().split('');
},
}
console.log(object.randomWord()); //"falconheavy"
console.log(object.wordSplit()); // ["t","e","s","l","a"]
Aucun commentaire:
Enregistrer un commentaire