gpt4 book ai didi

javascript - 为什么 array.push 会覆盖整个数组?

转载 作者:行者123 更新时间:2023-11-28 03:19:36 25 4
gpt4 key购买 nike

我向 api 发送一个 get 请求,它以

的形式返回数据
{
"message": "<SUCCESS>",
"result": [
{
"i": 1,
},
{
"i": 2,
},
{
"i": 3,
} ]
}

然后在javascript( Angular 组件.ts)中,我想创建一个数组ob对象,但是在将对象推送到数组中之后,每个数组都包含最后一个对象的数据:

.subscribe(
data => {
type MyArrayType = Array<UserOpinion>;
let array: MyArrayType = [];
let cont: CustomInterface = {
i: ''
}

data.result.forEach(function(entry) {
cont.i = entry["i"];

array.push(cont);
console.log(cont);
//right value is shown

})
//console.log(array)
//array contains the connect number of objects but the objects are set on the same value: "i" = 3

有什么想法为什么会发生这种情况吗?谢谢

最佳答案

这应该可以做到:

.subscribe(
data => {
type MyArrayType = Array<UserOpinion>;
let array: MyArrayType = [];

data.result.forEach(function(entry) {
array.push(entry);
});
}
);

您不需要 cont 只是将当前对象复制到另一个对象,您可以直接使用当前循环元素。

关于javascript - 为什么 array.push 会覆盖整个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59288742/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com