Implement Array-like behavior in JavaScript without using Array

后端 未结 10 1199
暖寄归人
暖寄归人 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 08:05

    If you're concerned about performance with your sparse array (though you probably shouldn't be) and wanted to ensure that the structure was only as long as the elements you handed it, you could do this:

    var sup = [];
    sup['0'] = 'z3ero';
    sup['1'] = 'o3ne';
    sup['4'] = 'f3our';        
    //sup now contains 3 entries
    

    Again, it's worth noting that you won't likely see any performance gain by doing this. I suspect that Javascript already handles sparse arrays quite nicely, thank you very much.

    0 讨论(0)
  • 2020-12-13 08:07

    Sure, you can replicate almost any data structure in JavaScript, all the basic building blocks are there. What you'll end up will be slower and less intuitive however.

    But why not just use push/pop ?

    0 讨论(0)
  • 2020-12-13 08:09

    [] operator is the native way to access to object properties. It is not available in the language to override in order to change its behaviour.

    If what you want is return computed values on the [] operator, you cannot do that in JavaScript since the language does not support the concept of computed property. The only solution is to use a method that will work the same as the [] operator.

    MyClass.prototype.getItem = function(index)
    {
        return {
            name: 'Item' + index,
            value: 2 * index
        };
    }
    

    If what you want is have the same behaviour as a native Array in your class, it is always possible to use native Array methods directly on your class. Internally, your class will store data just like a native array does but will keep its class state. jQuery does that to make the jQuery class have an array behaviour while retaining its methods.

    MyClass.prototype.addItem = function(item)
    {
        // Will add "item" in "this" as if it was a native array
        // it will then be accessible using the [] operator 
        Array.prototype.push.call(this, item);
    }
    
    0 讨论(0)
  • 2020-12-13 08:12

    Mostly you don't need a predefined index-size for arrays in javascript, you can just do:

    var sup = []; //Shorthand for an empty array
    //sup.length is 0
    sup.push(1); //Adds an item to the array (You don't need to keep track of index-sizes)
    //sup.length is 1
    sup.push(2);
    //sup.length is 2
    sup.push(4);
    //sup.length is 3
    //sup is [1, 2, 4]
    
    0 讨论(0)
提交回复
热议问题