Getter/setter on javascript array?

前端 未结 10 2178
闹比i
闹比i 2020-12-01 02:12

Is there a way to get a get/set behaviour on an array? I imagine something like this:

var arr = [\'one\', \'two\', \'three\'];
var _arr = new Array();

for (         


        
10条回答
  •  一生所求
    2020-12-01 02:33

    I looked up in John Resig's article JavaScript Getters And Setters, but his prototype example didn't work for me. After trying out some alternatives, I found one that seemed to work. You can use Array.prototype.__defineGetter__ in the following way:

    Array.prototype.__defineGetter__("sum", function sum(){
    var r = 0, a = this, i = a.length - 1;
    do {
        r += a[i];
        i -= 1;
    } while (i >= 0);
    return r;
    });
    var asdf = [1, 2, 3, 4];
    asdf.sum; //returns 10
    

    Worked for me in Chrome and Firefox.

提交回复
热议问题