gpt4 book ai didi

javascript - 如何在同一个列表中多次推送变量的值?

转载 作者:行者123 更新时间:2023-11-29 10:01:29 24 4
gpt4 key购买 nike

这是我的问题:我有一个函数,其中有一个变量,每次调用该函数时其值都会不断变化。稍后在函数代码中,我将变量放入列表中。但是当我这样做几次时,变量堆叠得很好,但所有值都与新值相同。

var new_plane; //I define these variables here because I want to use it again in other functions
var list_plane = [];

var Planes = { //I define the object
number: "",
airline: ""
};

function add_plane() {
new_plane = Planes;
new_plane.number = 10; //Random number
new_plane.airline = "Air France"; //Random airline of a list

list_plane.push(new_plane); //I push the variable in the list

for (let i = 0; i < list_plane.length; i++) {
document.body.innerHTML += list_plane[i].number + " " + list_plane[i].airline + "<br />"; //The body is used for the example and the output too
};
};

进入第一个位面后,一切正常。但是当设置第二个平面时,两个平面具有相同的值,而不是预期的各自的值。

最佳答案

移动

var Planes = { //I define the object
number: "",
airline: ""
};

在函数内部,否则数组中的每个元素都有相同的对象引用。


另一种解决方案是使用Plane 模式作为新对象的模板

// global
var Planes = {
number: "",
airline: ""
};

function add_plane() {
var new_plane = Object.assign({}, Planes); // get copy

new_plane.number = 10;
new_plane.airline = "Air France";

list_plane.push(new_plane);

for (let i = 0; i < list_plane.length; i++) {
document.body.innerHTML += list_plane[i].number + " " + list_plane[i].airline + "<br />";
} // no semicolon here
} // no semicolon here

关于javascript - 如何在同一个列表中多次推送变量的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56156676/

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