【发布时间】:2019-09-24 01:24:14
【问题描述】:
我正在通过重新使用以前设置的对象(Angular/Typescript)对 2 个暗淡对象数组进行分配。我的结果显示最后一个分配覆盖了前两个,我不知道为什么。你能看看我错过了什么吗?
export interface Criteria {
fieldValue: any;
fieldName: string;
childItems?: Criteria[];
}
// function to build my array of objects:
setCriteria() {
// parent object 1
// to be reused / reassigned to array below
const criteriaLevel1: Criteria = {
fieldName: 'Criteria name',
fieldValue: 'Crit-Level-1',
childItems: []
};
// parent object 2 - child of object 1
// to be reused / reassigned to array below
// into - childItems[0]
const criteriaLevel2: Criteria = {
fieldName: 'Criteria name',
fieldValue: 'Crit-Level-2',
childItems: []
};
// list of 3 different items to be assigned to array
// into - childItems[0].childItems[0] of each array record.
const itemsABC: string[] = [
'item AAA',
'item BBB',
'item CCC'
];
const criteriaArray = [];
let ix = 0;
itemsABC.forEach(item => {
console.log('item: ' + item);
criteriaArray[ix] = [];
criteriaArray[ix][0] = criteriaLevel1;
criteriaArray[ix][0].childItems[0] = criteriaLevel2;
criteriaArray[ix][0].childItems[0].childItems[0] = {
fieldName: 'name',
fieldValue: item + '-' + ix
};
ix++;
});
// output test
for (let i = 0; i < 3; i++) {
console.log('ix: ' + i);
for (const itemA of criteriaArray[i]) {
console.log('a: ' + itemA.fieldName + ' - ' + itemA.fieldValue);
for (const itemB of itemA.childItems) {
console.log('b: ' + itemB.fieldName + ' - ' + itemB.fieldValue);
for (const itemC of itemB.childItems) {
console.log('c: ' + itemC.fieldName + ' - ' + itemC.fieldValue);
}
}
}
}
}
我得到这个输出:
索引:0 - 插入项目:项目 AAA
索引:1 - 插入项目:项目 BBB
索引:2 - 插入项目:项目 CCC
ix: 0
a:条件名称 - Crit-Level-1
b:条件名称 - Crit-Level-2
c: name - item CCC-2 // 但我在这里期待:item AAA-0
ix: 1
a:条件名称 - Crit-Level-1
b:条件名称 - Crit-Level-2
c: name - item CCC-2 // 但我在这里期待:item BBB-1
ix: 2
a:条件名称 - Crit-Level-1
b:条件名称 - Crit-Level-2
c: name - item CCC-2 // 是,正如预期的那样:item CCC-2
我做错了什么?
【问题讨论】:
标签: javascript arrays angular typescript