我有一组对象(接口(interface))。
创建这个数组后,有了对象,我需要增加一个值 每个对象里面。 (“x1”到“x2”)。
迭代结束时,所有的'x1'和'x2'值为index的最新值。
let data: any = [];
let object: any = {
xaxis: null,
yaxis: null,
}
data.push(object)
data.push(object)
const doTHIS = () => {
const newData = data.map((item: any, index: any) => {
item.xaxis = 'x' + index + 1;
item.yaxis = 'y' + index + 1;
return item
});
return newData;
}
预期结果:
[ { xaxis: 'x1', yaxis: 'y1' }, { xaxis: 'x2', yaxis: 'y2' } ]
实际结果:
[ { xaxis: 'x2', yaxis: 'y2' }, { xaxis: 'x2', yaxis: 'y2' } ]
最佳答案
您将同一个对象两次插入数组。
该数组中的所有索引都指向同一个对象 (data[0] === data[1]
),因此循环中的每个更改都针对同一个对象。
从您的代码来看,在我看来您是编程新手。我想你想做的是:
let data = Array.from({ length: 2 }, (,index) => { //we don't need the first argument here
return {
xaxis: 'x' + (index + 1),
yaxis: 'y' + (index + 1),
};
});
console.log(data);
关于javascript - 无法增加界面中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57021483/