数组中的javascript随机项?

时间:2014-09-26 14:00:59

标签: javascript arrays random

所以我有一个strings: ["a", "b", "c", "d"]数组,但我希望array[4]每次使用时都是一个随机字符串,所以:

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",

有一个函数random(),但如果我将array[4]设置为等于random(),它将保持该随机值,但每次调用它时都需要保持随机。

4 个答案:

答案 0 :(得分:6)

使用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

答案 1 :(得分:1)

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

答案 2 :(得分:-1)

    function random() {
        character = String.fromCharCode(Math.floor( Math.random() * 26) + "a".charCodeAt(0));
        return character;
    }

答案 3 :(得分:-1)

以下是如何实现类似功能

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