仅当执行array.push时,将console.log(odgovor)放到Javascript代码中一次,它显示一切正常
getTacni() {
this.storageService.getQuestions().then(items => {
let odgovori: { id: number; answer: number }[] = [];
let odgovor: { id: number; answer: number } = { id: null, answer: null };
for (let i of items) {
odgovor.id = i.id;
odgovor.answer = i.tacan;
console.log(odgovor);
}
});
}
失败odgovori中的每个元素都相同
getTacni() {
this.storageService.getQuestions().then(items => {
let odgovori: { id: number; answer: number }[] = [];
let odgovor: { id: number; answer: number } = { id: null, answer: null };
for (let i of items) {
odgovor.id = i.id;
odgovor.answer = i.tacan;
odgovori.push(odgovor);
}
});
}
答案 0 :(得分:3)
在两个代码段中,您仅在内存中创建了一个对象,然后继续进行多次变异-而是在循环内创建每个对象:
getTacni() {
this.storageService.getQuestions().then(items => {
const odgovori: { id: number; answer: number }[] = [];
for (let i of items) {
const odgovor: { id: number; answer: number } = { id: i.id, answer: i.tacan };
odgovori.push(odgovor);
}
});
}
您还可以考虑使用.map
,这是一种简洁,实用且易读的方式,可以将一个数组的每个元素转换为另一个:
getTacni() {
this.storageService.getQuestions().then(items => {
const odgovor = items.map(({ id, tacan }) => ({ id, answer: tacan }));
});
}
答案 1 :(得分:0)
尝试一下:
Product Channel Account_Id Max_tier Balance Split_range
2000-0100 Direct 102123625 5000 174589.26 5000
2000-0100 Direct 102123625 10000 0 10000
2000-0100 Direct 102123625 20000 0 20000
2000-0100 Direct 102123625 50000 0 50000
2000-0100 Direct 102123625 99999999999.99 0 89589.26