-1

我有两个数组,我将它们实例化为对象。我想连接这两个数组,我想通过引用来做。有没有办法做到这一点?我知道对象是通过引用的,但据我所知。

// array 1
function gdb() {
    this.data = [{
        "id":"AA",
        "pos": "0"
    },
    {
        "id":"AB",
        "pos":"3"
    }
    ]
    ;
}

// array 2
function xdb() {
    this.data = [{
        "id":"CM",
        "pos": "4"
    },
    {
        "id":"CR",
        "pos":"7"
    }
    ]
    ;
}

// arrays combined
function gdb() {
    this.data = [{
        "id":"AA",
        "pos": "0"
    },
    {
        "id":"AB",
        "pos":"3"
    },
    {
        "id":"CM",
        "pos": "4"
    },
    {
        "id":"CR",
        "pos":"7"
    }
    ]
    ;
}
4

2 回答 2

1

要连接数组,只需使用他们的concat方法。不过,我不确定您所说的“通过引用”是什么意思。新数组(包含所有值)属性将指向与之前两个单独数组的属性相同的对象。但是,如果将新对象分配给旧数组属性,则新数组不会改变,这是完全不可能的。

于 2013-01-29T18:39:32.860 回答
0

数组是对象,默认情况下通过引用传递。我不确定您是否尝试将这些函数用作构造函数(看起来像)。这是你需要的吗?

function ConstructorOne() {
    this.data1 = [
        {"id":"AA", "pos":"0"},
        {"id":"AB", "pos":"3"}
    ];
}

function ConstructorTwo() {
    // Inheritance 
    ConstructorOne.call(this);

    this.data2 = [
        {"id":"CM", "pos":"4"},
        {"id":"CR", "pos":"7"}
    ];
}

var obj = new ConstructorTwo();
obj.data = obj.data1.concat(obj.data2);

// Delete old ones if not needed - don't otherwise
//delete obj.data1;
//delete obj.data2;

// Making changes to the data property, will also 
// change data1 & data2 from the constructors, proving 
// that data is just a reference of data1 + data2
obj.data[2]['id'] = "PIZZA";
obj.data[1]['id'] = "APPLE";
obj.data[0]['id'] = "LETTUCE";

console.log(obj);
于 2013-01-29T18:48:25.943 回答