简体   繁体   中英

javascript random item in array?

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.

Use Object.defineProperty .

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
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;
}
    function random() {
        character = String.fromCharCode(Math.floor( Math.random() * 26) + "a".charCodeAt(0));
        return character;
    }

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM