Any way to define getters for lazy variables in Javascript arrays?

后端 未结 5 1502
自闭症患者
自闭症患者 2021-01-04 05:50

I\'m trying to add elements to an array that are lazy-evaluated. This means that the value for them will not be calculated or known until they are accessed. This is like a p

5条回答
  •  悲哀的现实
    2021-01-04 06:12

    I don't particularly like this answer, but could you store your "variable" as an expression string, and then eval() it when you need it? Not ideal, but it's compact...

    var x = 10, arr = [];
    arr.push("x + 10");
    alert(eval(arr[0]));
    x = 20;
    alert(eval(arr[0]));
    

    I've tested it, and it works, even if it's not exactly what you're looking for.

提交回复
热议问题