javascript - 如果 indexOf 返回 0,为什么这段代码仍然向表中添加行?

标签 javascript jquery algorithm

我有这个 jQuery,它允许在单击按钮事件时向表中添加新行,但前提是尚未添加 id 值。

var factAgregada = [];

$('#btnAgregarFactura').on("click", function (e) {
    e.preventDefault();

    // no_factura and fecha_factura comes from a modal window 
    // it's not relevant to show that part here

    var no_factura = $("#no_factura").val(), 
        fecha_factura = $("#fecha_factura").val(),
        html;

    console.log(no_factura);
    console.log(factAgregada.indexOf(no_factura));

    if (factAgregada.indexOf(no_factura) >= -1) {
        html = '<tr>';
        html += '<td><input type="checkbox" id="' + no_factura + '"></td>';
        html += '<td>' + no_factura + '</td>';
        html += '<td>' + fecha_factura + '</td>';
        html += '</tr>';

        $(html).appendTo("#facturaBody");
    }

    factAgregada.push(no_factura);
});

在第一次执行时,代码运行良好,console.log() 输出如下:

 12
 -1

所以添加行是正确的,但是在第二次执行并保持相同的值 console.log() 从以前的值更改为这个值:

12
0

因此,不应该添加行但仍然添加到表中并继续执行 appendTo(),那里有什么问题?我没看到什么?

最佳答案

var factAgregada = [];

$('#btnAgregarFactura').on("click", function (e) {
    e.preventDefault();

    var no_factura = 10, 
        fecha_factura = 2,
        html;

    console.log(no_factura);
    console.log(factAgregada.indexOf(no_factura));

    if (factAgregada.indexOf(no_factura) == -1) {
        html = '<tr>';
        html += '<td><input type="checkbox" id="' + no_factura + '"></td>';
        html += '<td>' + no_factura + '</td>';
        html += '<td>' + fecha_factura + '</td>';
        html += '</tr>';

       console.log(html);
    }

    factAgregada.push(no_factura);
});

改变条件检查

view this fiddle

关于javascript - 如果 indexOf 返回 0,为什么这段代码仍然向表中添加行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26923268/

相关文章:

javascript - XHTML Transition 中的 iframe 不起作用

javascript按键多条记录问题

javascript - vue.js中获取数据属性的方法

javascript - KendoDropDownList TabIndex 不生效

javascript - img与js交换迭代超时

javascript - slideToggle 将 div 向上移动到内容上方

jQuery UI Datepicker - onSelect 获取所选日期 +3 天

python - 谁能教我如何进一步优化这个 'print up to the nth prime number' 脚本?

java - 所有排列的高效计算

Java 需要解释我的词典顺序算法