首页 > 解决方案 > 如何避免 .each 方法中的重复值

问题描述

附加表代码

var tr = '<tr id="trdata" ><td class="code" >'+item_name+'</td><td class="itemname" >'+item_name2+'</td> <td class="qty" >'+qty+'</td><td class="rate" >'+rate+'</td> <td class ="grand">'+total+'</td> <td><button type = "button" class="btn btn-danger btn-xs" >Remove</button></td></tr>';
$('tbody').append(tr);
    $("#form2")[0].reset();
}

价值获取代码

$('#save').click(function(){
    var code      = [];
    var itemname  = [];
    var qty       = [];
    var rate      = [];
    var grand     = [];

    $('.code').each(function(){code.push($(this).text());});
    $('.itemname').each(function(){itemname.push($(this).text());});
    $('.qty').each(function(){qty.push($(this).text());});
    $('.rate').each(function(){rate.push($(this).text());});
    $('.grand').each(function(){grand.push($(this).text());});
}); 

在我的控制台中显示重复值

"console.log(code);"
[]
0: "3"
1: "3"
length: 2

如何避免这种重复,它在使用插入查询时也插入到我的数据库中

标签: jquery

解决方案


你可以测试.includes()

$('.code').each(function(){
    if (!code.includes($(this).text()) {
        code.push($(this).text());
    }
});

但是,如果您需要保持所有数组同步,您应该在行上使用一个循环,而不是为每个字段单独循环。

$("tr").each(function() {
    var curCode = $(this).find(".code").text();
    if (!code.includes(curCode)) {
        code.push(curCode);
        itemname.push($(this).find(".itemname").text());
        qty.push($(this).find(".qty").text());
        rate.push($(this).find(".rate").text());
        grand.push($(this).find(".grand").text());
    }
});


推荐阅读