2

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.

4
  • 3
    Instead of calling array[4] - just call random()? Commented Sep 26, 2014 at 14:02
  • 1
    This seems like something better suited for javascript object/class using getters and setters Commented Sep 26, 2014 at 14:03
  • No I want to call array[4] not random, I know it's a bit vague Commented Sep 26, 2014 at 14:04
  • +1 to this question that made me learn something I could not think was possible! Commented Sep 26, 2014 at 14:27

4 Answers 4

7

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
Sign up to request clarification or add additional context in comments.

3 Comments

nice! Didn't know that!
@FrancescoMM the nice thing about Object.defineProperty is it doesn't require any special syntax and it works after the object is instantiated. If you don't mind special-purpose syntax and can get away with setting up the accessor during instantiation, your solution works too (+1 to you).
..but mine is not even an array.. :(
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;
}

Comments

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

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.