关于JavaScript中的字符比较

根据路由我input地址空白localhost:3000 / ff00ff

这里'ff00ff',它应该像一个hex代码,如果是,回复你好世界,'ff00ff'! 如果不是,则回复404找不到。

但问题是,这是行不通的。 提示:“错误:未捕获的错误:回复接口调用两次”

这是我写的代码

server.route({ method: 'GET', path: '/{name}', handler: function (request, reply) { var judge = new String(request.params.name); console.log(judge); for(var i=0; i<6; i++){ if (judge[i]==='0'||'1'||'2'||'3'||'4'||'5'||'6'||'7'||'8'||'9'||'a'||'b'||'c'||'d'||'e'||'f'||'A'||'B'||'C'||'D'||'E'||'F'){ reply('Hello, ' + judge + '!') } else{ reply('404 Page Not Found') } } } }); 

您的比较试图将所有字符放在一起,JavaScript将简单评估为'0' ,从而在所有非零字符的judge[i]==='0'上产生false

为了比较,你必须分别做每个比较。 即:

 if (judge[i] === '0' || judge[i] === '1' || ...) { // ... 

然而 ,要实现你想要做的事情有一个更简单的方法。

inputRegExp和String.match函数。

 if (judge.match(/^[A-F0-9]{6}$/i)) { // ... 

这将检查judge是只包含AF(或AF)和0-9的6个字符的string。