gpt4 book ai didi

javascript - 如何将多个对象添加到对象内的数组中

转载 作者:行者123 更新时间:2023-12-02 17:42:45 25 4
gpt4 key购买 nike

下面的代码会将最后生成的对象添加到 Person 对象的phones 数组中。我想做的是将所有生成的对象添加到phones数组中。

var person = {
username : username,
phones : []
}

// Added Profile
var phoneObjs = {};
var addedPhones = $('.added_phone');

循环遍历所有新的 .added_phone 输入值的函数:

addedPhones.each( function(i) {
var tag = $(this).children("label").text();
var value = $(this).children("input").val();
phoneObjs = $(this).map(function(i,el) {
var $el = $(el);
return {
tag: tag,
label: value
}
}).get();

console.log(phoneObjs);

person.phones = phoneObjs;
// person.phones.push(phoneObjs);

console.log(person.phones);
});

我将创建 2 个新的输入字段并输入 2 个不同的数字,接下来我提交表单并运行上面的函数。从 Chrome 控制台 console.log(person.phones):

enter image description here

第二次循环时,第一个对象被替换
enter image description here

如何避免这个问题?

最佳答案

在 ES5 中

person.phones = person.phones.concat(phoneObjs);

在 ES6 中:

person.phones = [...person.phones,...phoneObjs];

关于javascript - 如何将多个对象添加到对象内的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22048025/

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