Implement Array-like behavior in JavaScript without using Array

后端 未结 10 1206
暖寄归人
暖寄归人 2020-12-13 07:45

Is there any way to create an array-like object in JavaScript, without using the built-in array? I\'m specifically concerned with behavior like this:

var sup         


        
10条回答
  •  抹茶落季
    2020-12-13 07:51

    Is this what you're looking for?

    Thing = function() {};
    Thing.prototype.__defineGetter__('length', function() {
        var count = 0;
        for(property in this) count++;
        return count - 1; // don't count 'length' itself!
    });
    
    instance = new Thing;
    console.log(instance.length); // => 0
    instance[0] = {};
    console.log(instance.length); // => 1
    instance[1] = {};
    instance[2] = {};
    console.log(instance.length); // => 3
    instance[5] = {};
    instance.property = {};
    instance.property.property = {}; // this shouldn't count
    console.log(instance.length); // => 5
    

    The only drawback is that 'length' will get iterated over in for..in loops as if it were a property. Too bad there isn't a way to set property attributes (this is one thing I really wish I could do).

提交回复
热议问题