Reputation: 335
So I have an array of strings: ["a", "b", "c", "d"]
, but I want array[4]
to be a random string each time it is used, so:
array[0] returns "a",
array[1] returns "b",
array[4] returns something random, like "x",
array[4] returns something random the second time as well, like "y",
There is a function random(), but if I set array[4]
equal to random() it will hold on to that random value, but it needs to stay random every time it is called.
Upvotes: 2
Views: 139
Reputation: 2960
var array = { get 4() {return getRandomInt(1,10);} }
alert(array[4]);
alert(array[4]);
alert(array[4]);
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
Upvotes: 1
Reputation: 513
Here's how you could accomplish similar functionality
arrayManager = {
array: ["a", "b", "c", "d"]
set: function(i, v) {
this.array[i] = v;
}
get: function(i) {
if (i == 4) return random();
else return this.array[i];
}
};
var random = arrayManager.get(4);
Upvotes: -1
Reputation: 114
function random() {
character = String.fromCharCode(Math.floor( Math.random() * 26) + "a".charCodeAt(0));
return character;
}
Upvotes: -1
Reputation: 76786
var a = ["a", "b", "c", "d"];
Object.defineProperty(a, 4, { get: Math.random });
console.log(a[4]); // some random number
console.log(a[4]); // another random number
Upvotes: 7