Getter/setter on javascript array?

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

    It is possible to define Getters and Setters for JavaScript arrays. But you can not have accessors and values at the same time. See the Mozilla documentation:

    It is not possible to simultaneously have a getter bound to a property and have that property actually hold a value

    So if you define accessors for an array you need to have a second array for the actual value. The following example illustrates it.

    //
    // Poor man's prepare for querySelector.
    //
    // Example:
    //   var query = prepare ('#modeler table[data-id=?] tr[data-id=?]');
    //   query[0] = entity;
    //   query[1] = attribute;
    //   var src = document.querySelector(query);
    //
    var prepare;
    {
      let r = /^([^?]+)\?(.+)$/; // Regular expression to split the query
    
      prepare = function (query, base)
      {
        if (!base) base = document;
        var q  = []; // List of query fragments
        var qi = 0;  // Query fragment index
        var v  = []; // List of values
        var vi = 0;  // Value index
        var a  = []; // Array containing setters and getters
        var m;       // Regular expression match
        while (query) {
          m = r.exec (query);
          if (m && m[2]) {
            q[qi++] = m[1];
            query   = m[2];
            (function (qi, vi) {
              Object.defineProperty (a, vi, {
                get: function() { return v[vi]; },
                set: function(val) { v[vi] = val; q[qi] = JSON.stringify(val); }});
            })(qi++, vi++);
          } else {
            q[qi++] = query;
            query   = null;
          }
        }
        a.toString = function () { return q.join(''); }
        return a;
      }
    }
    

    The code uses three arrays:

    1. one for the actual values,
    2. one for the JSON encoded values
    3. and one for the accessors.

    The array with the accessors is returned to the caller. When a set is called by assigning a value to the array element, the arrays containing the plain and encoded values are updated. When get gets called, it returns just the plain value. And toString returns the whole query containing the encoded values.

    But as others have stated already: this makes only sense, when the size of the array is constant. You can modify the existing elements of the array but you can not add additional elements.

提交回复
热议问题