跨浏览器的方式将JavaScript数组子类化并获得数组[i]方法?

跨浏览器的方式将JavaScript数组子类化并获得数组[i]方法?,javascript,arrays,browser,subclass,Javascript,Arrays,Browser,Subclass,非常高兴了解到JavaScript数组基本上是子类化的(代码从链接复制): 但这还不完全。有没有办法像这样伪造数组的子类并获得[]方法 var a = []; a[3] = true; console.log(a.length); //=> 4 var s = new SomeType(); s[3] = true; console.log(s.length); //=> 1 这样,在执行for循环时,仍然可以将其视为数组: for (var i = 0; i < s.

非常高兴了解到JavaScript
数组基本上是子类化的(代码从链接复制):

但这还不完全。有没有办法像这样伪造数组的子类并获得
[]
方法

var a = [];
a[3]  = true;
console.log(a.length); //=> 4

var s = new SomeType();
s[3]  = true;
console.log(s.length); //=> 1
这样,在执行for循环时,仍然可以将其视为数组:

for (var i = 0; i < s.length; i++) {
  var item = s[i];
}
for(变量i=0;i
仅适用于带有
\uuuuu proto\uuuuu
(已弃用)的浏览器,因此它不是跨浏览器的:

var CustomArray = function ( ) {
  var array = [ 16 ];
  array.__proto__ = this.__proto__;
  return array;
};

CustomArray.prototype = [];
CustomArray.prototype.constructor = CustomArray;

var array = new CustomArray( );
console.log( array instanceof Array );       // true
console.log( array instanceof CustomArray ); // true

array[ 3 ] = 42;
console.log( array.length );                 // 4

我认为没有其他方法可以做到这一点。

我发现,对“数组”进行子类化的最好方法不是对“数组”进行子类化,而是对另一个“类似数组的对象”进行子类化,它们有很多,一个是使用集合。基本上,它完成了数组所做的一切(包括括号表示法),但它是一个“自定义”原型,因此可以轻松地对其进行子类化,这与本机原型不同,本机原型在子类化时通常会出现问题


这是一个问题。。。我认为没有跨浏览器的方法来解决这个问题。我想到两件事:1。属性-不是真正的跨浏览器2。只要强制执行
.push
,这就行了——如果可能的话。这似乎是相关的:为什么还要对数组进行子类化?您可以创建一个数组,但仍可以将新属性附加到该数组。
var CustomArray = function ( ) {
  var array = [ 16 ];
  array.__proto__ = this.__proto__;
  return array;
};

CustomArray.prototype = [];
CustomArray.prototype.constructor = CustomArray;

var array = new CustomArray( );
console.log( array instanceof Array );       // true
console.log( array instanceof CustomArray ); // true

array[ 3 ] = 42;
console.log( array.length );                 // 4
var MySubArray = function(){
  Collection.apply(this, arguments);
  this.myCustomMethod = function(){
    console.log("The second item is "+this[1]);
  };
};
MySubArray.prototype = Object.create(Collection.prototype);

var msa = new MySubArray("Hello", "World");
msa[2] = "Third Item";
console.log(msa);
msa.myCustomMethod();