引用数组切片 [英] Reference to slice of an array

查看:58
本文介绍了引用数组切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取对数组切片的引用?

How to get the reference to a slice of an array?

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)

It works for direct slices derived from A. But, how to get it for all slices derived? (in this case for 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数组来做到这一点(嗯,无论如何都不是直接的方式).

I don't think you can do this with native JS arrays (well, not in a straightforward manner anyway).

我认为最干净的方法是返回并使用自定义对象表示切片.也许符合以下几点:

I think the cleanest approach would be going back and using custom objects to represent the slices. Perhaps something along these lines:

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很烦人且容易出错,我不相信有一种跨浏览器的方式运算符重载.

Of course, this loses the convenient [] syntax and the objects aren't arrays anymore but subclassing Array is annoying and error prone and I don't believe there is a cross-browser way to do operator overloading.

这篇关于引用数组切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆