在打字稿中:
我有一个一维对象数组:my1dArray
。
我将my1dArray
的每行5倍复制到2D数组my2dArray
中(所以我最终得到了my2dArray[3][5]
)。
然后我重置my2dArray
每行的id元素。
对于my2dArray[0]
,我最终得到了这个(id = 4):
{id: 4, surname: "Smith", givenNames: "Linda"}
{id: 4, surname: "Smith", givenNames: "Linda"}
{id: 4, surname: "Smith", givenNames: "Linda"}
{id: 4, surname: "Smith", givenNames: "Linda"}
{id: 4, surname: "Smith", givenNames: "Linda"}
我以为我会得到的是
{id: 0, surname: "Smith", givenNames: "Linda"}
{id: 1, surname: "Smith", givenNames: "Linda"}
{id: 2, surname: "Smith", givenNames: "Linda"}
{id: 3, surname: "Smith", givenNames: "Linda"}
{id: 4, surname: "Smith", givenNames: "Linda"}
my2dArray[4][5]
数组的其余部分也有相同的问题。
我在做什么错了?
//Create 1d Array
let my1dArray: any[];
my1dArray = [
{ id: 0, surname: 'Smith', givenNames: 'Linda'},
{ id: 0, surname: 'Bloggs', givenNames: 'Bill'},
{ id: 0, surname: 'Jones', givenNames: 'Jim'},
];
//Initalise 2d Array
let my2dArray = init2DArray(3, 5, function () {
return 0
});
let j = 0;
let k = 0;
for (let i = 0; i < my1dArray.length; i++) {
for (let count = 0; count < 5; count++) {
my2dArray[j][count] = my1dArray[i];
//reset the id
my2dArray[j][count].id = k;
k++;
}
j++;
}
console.log('myNewData', my2dArray[0]);
/////Intialisation function///////////////
function init2DArray(xlen, ylen, factoryFn) {
let ret = [];
for (let x = 0; x < xlen; x++) {
ret[x] = [];
for (let y = 0; y < ylen; y++) {
ret[x][y] = factoryFn(x, y)
}
}
return ret
}
答案 0 :(得分:0)
实际上,您并不复制my1dArray
的每一行。此作业:
my2dArray[j][count] = my1dArray[i];
仅使用对my2dArray
中相同对象的引用来填充my1dArray
。因此,当您更改id
时,每次在您的内部循环中都对同一个对象执行此操作。
要在JS中正确复制对象,您可能需要阅读this。对于浅表副本(足够用于示例代码),可以使用Object.assign()
。
下面的工作代码段:
//Create 1d Array
let my1dArray: any[];
my1dArray = [{
id: 0,
surname: 'Smith',
givenNames: 'Linda'
},
{
id: 0,
surname: 'Bloggs',
givenNames: 'Bill'
},
{
id: 0,
surname: 'Jones',
givenNames: 'Jim'
},
];
//Initalise 2d Array
let my2dArray = init2DArray(3, 5, function() {
return 0
});
let j = 0;
let k = 0;
for (let i = 0; i < my1dArray.length; i++) {
for (let count = 0; count < 5; count++) {
my2dArray[j][count] = Object.assign({}, my1dArray[i]);
//reset the id
my2dArray[j][count].id = k;
k++;
}
j++;
}
function init2DArray(xlen, ylen, factoryFn) {
let ret = [];
for (let x = 0; x < xlen; x++) {
ret[x] = [];
for (let y = 0; y < ylen; y++) {
ret[x][y] = factoryFn(x, y)
}
}
return ret
}
console.log(my2dArray)