猿问

我正在尝试制作一个小型分词器

我正在尝试在 js 中制作一个 tokenzir,但我注意到结果中没有包含“+”,因为我想要这段代码中的错误是什么


var a=String.raw`(0.34+4+5.5++4() )`

function tokenizer(a){var b=0;d=[];e="";

while(b<a.length){var c=a[b];

    if(c=="+"){d.push("+");c=a[++b];continue;}

    if(c=="("){d.push(c);b++;continue;}

    if(c==")"){d.push(c);b++;continue;}

    if(c==" "||c=="\n"||c=="\t"){b++;continue;}

    if(/[0-9.]/.test(c)==true){while(/[0-9.]/.test(c)==true){e+=c;c=a[++b]};d.push(e);e="";b++;continue}

}

return d;

}

console.log(tokenizer(a))//result =["(", "0.34", "4", "5.5", "+", "4", ")", ")"]

我希望你的结果 ["(", "0.34","+", "4","+", "5.5","+, "+", "4", ")", ")"]


摇曳的蔷薇
浏览 98回答 1
1回答

白板的微信

让我的评论成为答案:不要同时使用所有的[++b]and索引和递增。[b++]它使代码更难阅读并且更容易出错,就像您的情况一样 - 删除最后一个b++(继续之前的那个)可以解决问题(见下文)。我更喜欢在命令之后使用索引和增量(对于++b)工作代码:var a=String.raw`(0.34+4+5.5++4() )`function tokenizer(a){var b=0;d=[];e="";&nbsp; &nbsp; while(b<a.length){var c=a[b];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(c=="+"){d.push("+");c=a[++b];continue;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(c=="("){d.push(c);b++;continue;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(c==")"){d.push(c);b++;continue;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(c==" "||c=="\n"||c=="\t"){b++;continue;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(/[0-9.]/.test(c)==true){while(/[0-9.]/.test(c)==true){e+=c;c=a[++b]};d.push(e);e="";continue}&nbsp; &nbsp; }&nbsp; &nbsp; return d;}console.log(tokenizer(a))输出:[&nbsp; '(', '0.34', '+',&nbsp; '4', '+',&nbsp; &nbsp; '5.5',&nbsp; '+', '+',&nbsp; &nbsp; '4',&nbsp; '(', ')',&nbsp; &nbsp; ')']我认为还可以使代码更清晰:缩进并将代码拆分为更多行,每行一个命令使用有意义的变量名。同样,您节省了一些空间和写作,但代价是代码的可读性较差。并因此以更困难的调试为代价:-)
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答