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

image.png
在做这个动态添加字段的时候遇到的问题
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; //阻止表单跳转。如果需要表单跳转,去掉这段即可。
                });
阅读 2.4k
1 个回答

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的值,所以最终数组中所有的元素都是该对象(同一个)。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题