js arrays.push在for循环中添加元素输出重复如何解决?

作者站长头像
站长
· 阅读数 17

js arrays.push在for循环中添加元素输出重复如何解决?在做这个动态添加字段的时候遇到的问题currentid 是判断有多少个字段 图上字段2时currentid就是2多字段名称是name_1 ,name_2这样一次类推 点击添加就会追加 问题是 for循环中 处处的这个name是正确的 但是在for循环中打印就是只有最后一个

form.on('submit(*)',function(data) {
                    var arrays=new Array();
                    //JSON.stringify() 不能转下标非1,2,3这种数字的数组,
                    //所以采用新建对象的方式添加数据
                    var products={};
                    var for_id=1;
                    //console.log(currentid);
                    for(let index=0; index<currentid; index++) {
                        products['name']=$("#name_"+for_id+"").val();

                        console.log(products['name']);
                        // products['type']=$("input[name='type_"+for_id+"']:checked").val();//终端
                        // if(products['type']=="text") {
                        //     $("#cf"+for_id+"").is(':checked')? 1:0;
                        //     products['option']=$("#cf_"+for_id+"").val();//终端
                        // }
                        // if(products['type']=="radio") {

                        //     products['option']=$("#value_"+for_id+"").val();//终端
                        // }
                        // if(products['type']=='checkbox') {
                        //     products['option']=$("#value_"+for_id+"").val();//终端
                        // }
                        arrays.push(products);
                        for_id++;

                    }
                    var json_arrays=JSON.stringify(arrays);
                    console.log(json_arrays);

                    return false; //阻止表单跳转。如果需要表单跳转,去掉这段即可。
                });
回复
1个回答
avatar
test
2024-07-16

var products={};放到for循环内部。

var arrays = new Array();

for(let index=1; index<=currentid; index++) {
    //所以采用新建对象的方式添加数据
    const products = {};
    products['name'] = $("#name_"+index+"").val();
    console.log(products['name']);
    arrays.push(products);
}

引申一点:

JS的数据存储:

  • 原始数据类型:栈内存原始数据类型直接存储在栈(stack)中的简单数据段,占据空间小、大小比较稳定,属于被频繁使用数据,所以放入栈中存储。
  • 引用数据类型:堆内存引用数据类型存储在堆(heap)中的对象,占据空间大、大小不固定。在栈内存中只是存了一个地址来表示对堆内存中的引用。

对象,也即代码中的products是存储在堆中的。数组arrays中push的是对for外部的引用,而非拷贝(这块还涉及到深拷贝、浅拷贝)。对products的修改,会影响到数组arrays

你代码的问题相当于,只创建了一个products对象,每次push到数组后,再修改这一个products的值,所以最终数组中所有的元素都是该对象(同一个)。

回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容