Getter/setter on javascript array?

前端 未结 10 2219
闹比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:36

    You can add whatever methods you like to an Array, by adding them to Array.prototype. Here's an example that adds a getter and setter

    Array.prototype.get = function(index) {
      return this[index];
    }
    
    Array.prototype.set = function(index, value) {
      this[index] = value;
    }
    

提交回复
热议问题