如何获取对数组切片的引用?
var A = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
A.mySlice = function(l, h){return this.slice(l,h)};
var B = A.mySlice(1,5); // ["b", "c", "d", "e"]
它适用于从 A 派生的直接切片。但是,如何为所有派生的切片获取它? (在这种情况下为 B)
B.mySlice = function(l, h){return this.slice(l,h)};
A[3] = 33;
A.mySlice(1,5) // ["b", "c", 33, "e"] => ok
B.mySlice(0,3) // ["b", "c", "d"] => I would want ["b", "c", 33]
最佳答案
我不认为你可以使用原生 JS 数组来做到这一点(好吧,无论如何都不能以直接的方式)。
我认为最干净的方法是返回并使用自定义对象来表示切片。也许沿着这些思路:
function ArraySlice(arr, lo, hi){
this.arr = arr;
this.lo = lo;
this.hi = hi;
this.length = hi - lo;
};
ArraySlice.prototype._contains = function(ix){
return this.lo + ix < this.hi;
};
ArraySlice.prototype.get = function(ix){
if (this._contains(ix)){
return this.arr[this.lo + ix];
}else{
return; //undefined
}
};
ArraySlice.prototype.set = function(ix, value){
if (this._contains(ix)){
return (this.arr[this.lo + ix] = value);
}else{
return; //undefined
}
};
var a = [0,1,2,3,4,5];
var b = new ArraySlice(a, 1, 3);
a[2] = 17;
console.log( b.get(1) );
当然,这失去了方便的 []
语法并且对象不再是数组,但是子类化 Array 很烦人而且容易出错,我不相信有跨浏览器的方法做运算符重载。
关于javascript - 引用数组的切片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9524354/