我有两个我实例化为对象的数组。我想连接这两个数组,我想通过引用来做。有没有办法做到这一点?我知道对象是参考,但就我而言。
// 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"
}
]
;
}
答案 0 :(得分:1)
要连接数组,只需使用他们的concat
method。不过,我不确定你的“引用”是什么意思。新数组(包含所有值)属性将指向与之前两个单独数组的属性相同的对象。但是,如果将新对象分配给旧数组属性,新数组将不会更改,这是非常不可能的。
答案 1 :(得分: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);