Implement Array-like behavior in JavaScript without using Array

后端 未结 10 1213
暖寄归人
暖寄归人 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:47

    Yes, you can subclass an array into an arraylike object easily in JavaScript:

    var ArrayLike = function() {};
    ArrayLike.prototype = [];
    ArrayLike.prototype.shuffle = // ... and so on ...
    

    You can then instantiate new array like objects:

    var cards = new Arraylike;
    cards.push('ace of spades', 'two of spades', 'three of spades', ... 
    cards.shuffle();
    

    Unfortunately, this does not work in MSIE. It doesn't keep track of the length property. Which rather deflates the whole thing.

    The problem in more detail on Dean Edwards' How To Subclass The JavaScript Array Object. It later turned out that his workaround wasn't safe as some popup blockers will prevent it.

    Update: It's worth mentioning Juriy "kangax" Zaytsev's absolutely epic post on the subject. It pretty much covers every aspect of this problem.

提交回复
热议问题