编写简单的一行代码时出现意外错误

unexpected error occur when writing a simple line of code

这里有一个函数,它把一个字符串变成一个特定的代码,另一个函数,把那个代码解码成一个可读的字符串,它们看起来像这样:(问题出在decoder函数中)

 var hr = [['A','B','C','D','E','F','G','H','I','J'],
          ['a','b','c','d','e','f','g','h','i','j'],
          ['K','L','M','N','O','P','Q','R','S','T'],
          ['k','l','m','n','o','p','q','r','s','t'],
          ['U','V','W','X','Y','Z','0','1','2','3'],
          ['4','5','6','7','8','9','!','@','#','$'],
          ['%','^','&','*','(',')','-','=','_','+'],
          ['[',']','{','}',':',';',',','/','.','<'],
          ['>','?',' ','u','v','w','x','y','z']];



function coder(str){
    str = str.replace(/[ ]+/g,'');
    str = str.split('');// now str is an Array
    var code ='';

    for(var i=0;i<str.length;i++){ // now suppose i here is A
    //console.log(str[i])
        for(var j=0; j<hr.length;j++){
            for(var k=0;k<hr[j].length;k++){
                if(hr[j][k] === str[i]){
                    code = code+'#'+String(j)+'@'+String(k)+'~';
                }// end of if statement
            }// end of k loop
        }// end of j loop
    }// end of i loop

    return code;
};// end of coder function

function decoder(code){
    code = code.split('~');
    console.log(code);
    var str = '',x,y;
    for(var i=0;i<code.length;i++){
        code[i] = code[i].replace('#','');
        code[i] = code[i].split('@');
        code[i][0] = parseInt(code[i][0]);code[i][1] = parseInt(code[i][1])
    };// end of i loop
    console.log(code);

    for(var j=0;j<code.length;j++){ // now suppose j  is right now [1,2]
        x = code[j][0];
        y = code[j][1];
        str = str + hr[x][y];
        /*console.log(x);console.log(y);
        console.log(hr[x][y])*/
    };  
    return str;
}// end of decode function

问题出在 decoder 函数中。我没有看到任何可能引发 javascript 引擎抛出错误的东西,但事实是它正在抛出错误。

问题与错误

错误的名称是 TypeError: Cannot read property 'NaN' of undefined。我在这里没有看到任何未定义的东西,就 NaN 而言,然后定义了 x 和 y。

这个你自己看吧。
decoder(coder('sanmveg')) 给出 错误

调试>思考>迷茫

我使用调试技术找出问题,发现错误在那行str=str+hr[x][y]。所以 NaN 被引用到 xyundefined 可能被引用到 hr 但所有这些都被定义为

我不知道为什么这不起作用并给我 错误


这里有什么错误?请对此提供可能的解释,以提高此 post 的质量。
感谢您的贡献和回复

这对我有用,还没有再看一遍如何最好地清理它: http://jsfiddle.net/w5ozg373/3/

你有:

code = code.split('~');

添加:

// add this piece
if(code[code.length -1].trim().length == 0) {
    code.pop();   
}

当您使用 split 时,您会得到一个空字符串的标记。

也许这样可以清理它? :

code = code.filter(function(code_item) {
    return code_item.trim().length > 0; 
});

http://jsfiddle.net/w5ozg373/4/