javascript将对象推送到for循环处的数组会更改前端组件
我试图每次推送不同的对象,但它会在循环for循环时更改前面的组件。这是我的密码javascript将对象推送到for循环处的数组会更改前端组件,javascript,arrays,object,Javascript,Arrays,Object,我试图每次推送不同的对象,但它会在循环for循环时更改前面的组件。这是我的密码 let responseArray = []; const sendBatchRequest = async function (response) { try { console.log(`response: ${JSON.stringify(response)}`); if (responseArray.length < 9) { respo
let responseArray = [];
const sendBatchRequest = async function (response) {
try {
console.log(`response: ${JSON.stringify(response)}`);
if (responseArray.length < 9) {
responseArray.push(response); // push 9 components
console.log(`responseArray at if: ${JSON.stringify(responseArray)}`);
} else {
responseArray.push(response); // push last 10th component
console.log(`responseArray at else: ${JSON.stringify(responseArray)}`);
for (let i = 0; i < responseArray.length; i++) {
console.log(`responseArray ${i} - ${JSON.stringify(responseArray[i])}`);
}
// do something...
responseArray = []; // reset the array
}
} catch (err) {
console.log(`sendBatchRequest err: ${err}`);
}
}
const main = async function () {
try {
const result = {};
for (let i = 0; i < 5; i++) {
result.data = i;
await sendBatchRequest(result);
}
} catch (err) {
console.log(`main err: ${err}`);
}
}
main();
我不明白为什么在第2个循环中,
responseArray[0]
将{“数据”:0}
更改为{“数据”:1}
。我希望我的responseArray
看起来像[{“数据”:0},{“数据”:1”},
。数组上发生了什么。在javascript上推(对象)?我如何得到我想要的结果?每次都将相同的对象引用(不是副本)推到数组中。因此for循环的每次迭代都会修改该对象
更改:
const result = {};
for (let i = 0; i < 5; i++) {
result.data = i;
await sendBatchRequest(result);
}
constresult={};
for(设i=0;i<5;i++){
结果:数据=i;
等待sendBatchRequest(结果);
}
到
for(设i=0;i<5;i++){
//每次迭代都要创建新对象
const result={data:i};
等待sendBatchRequest(结果);
}
这是因为每次result.data更改时,您都将结果变量作为引用传递,因此responseArray
上的推送项也将更改
为了避免这种情况,请改为:
let responseArray=[];
const sendBatchRequest=异步函数(响应){
试一试{
log(`response:${JSON.stringify(response)}`);
如果(响应时间长度<9){
responseArray.push(响应);//推9个组件
log(`responseArray at-if:${JSON.stringify(responseArray)}`);
}否则{
responseArray.push(响应);//推最后一个组件
log(`responseArray at else:${JSON.stringify(responseArray)}`);
for(设i=0;i
const result = {};
for (let i = 0; i < 5; i++) {
result.data = i;
await sendBatchRequest(result);
}
for (let i = 0; i < 5; i++) {
// new object each iteration
const result = {data : i};
await sendBatchRequest(result);
}