Creating array-like objects in JavaScript

后端 未结 5 1245
轻奢々
轻奢々 2020-12-02 15:53

In JavaScript, there are objects that pretend to be arrays (or are \"array-like\"). Such objects are arguments, NodeLists (returned from get

5条回答
  •  失恋的感觉
    2020-12-02 16:49

    Look at this :

    var ArrayLike = (function () {
    
     var result;
    
     function ArrayLike(n) {
    
         for (var idx = 0; idx < n; idx++) {
             this[idx] = idx + 1;
         }
    
         // this.length = Array.prototype.length; THIS WILL NOT WORK !
    
     }
    
    
     // ArrayLike.prototype.splice = Array.prototype.splice; THIS WILL NOT WORK !
    
    
     // THIS WILL WORK !
     Object.defineProperty(ArrayLike.prototype, 'length', {
    
         get: function() {
    
             var count = 0, idx = 0;
    
             while(this[idx]) {
                 count++;
                 idx++;
             }
             return count;
    
         }
    
     });
    
    
     ArrayLike.prototype.splice = Array.prototype.splice;
    
    
     ArrayLike.prototype.multiple = function () {
    
         for (var idx = 0 ; idx < this.length ; idx++) {
    
             if (result) {
                 result = result * this[idx];
             } else {
                 result = this[idx];
             }
         }
    
         return result;
     };
    
     return ArrayLike
     })();
    
    var al = new ArrayLike(5);
    
    al.__proto__ = ArrayLike.prototype;
    
    console.log(al.length, al.multiple(), al); 
    

    This will display in Chrome : 5 120 [1, 2, 3, 4, 5]

提交回复
热议问题