【问题标题】:Table Cell loop produces undefined index erroneously表格单元循环错误地产生未定义的索引
【发布时间】:2014-03-02 17:21:50
【问题描述】:
$('#process').click(function() {
    var char_matrix = [];
    $('#char_input tr').each(function(e) {
        $(this).children('td').each(function() {
            var a = $(this).css('background-color').replace(/\D+/g, '');
            if (a === '2551650') {
                char_matrix[e] += "0";
            } else {
                char_matrix[e] += "1";
            }//END IF
        });//END EACH
        alert(char_matrix[e]);
    });//END EACH
});//END FUNC

此代码循环遍历每个表格行和每个行单元格以创建一个由 1 和 0 组成的数组。数组的每个索引是不同的行,每个索引由一系列 1 和 0 组成,表示每行的背景颜色状态。预期输出类似于:

10101010
10101010
10101010
10101010
10101010
10101010
10101010
10101010

实际输出为:

undefined10101010
undefined10101010
undefined10101010
undefined10101010
undefined10101010
undefined10101010
undefined10101010
undefined10101010

我不知道是什么导致每行在开始时未定义,这很烦人。除了正确的 8 个二进制值之外,未定义的索引实际上被添加到数组中。我尝试将 char_matrix 定义为全局和局部变量,但无济于事。

我也意识到我可以直接使用 Javascript,但这不是我在这个项目中的选择。

【问题讨论】:

    标签: javascript jquery arrays loops indexing


    【解决方案1】:

    这一行之后

    $('#char_input tr').each(function(e) {
    

    添加这一行

      char_matrix[e] = ""
    

    否则char_matrix[e] 最初是未定义的。这与您的结果一致,因为

    undefined + "1" === "undefined1"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-08
      • 2014-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-12
      • 2018-10-21
      相关资源
      最近更新 更多