[英]Function to test regular expression
我在Eloquent Javascript书籍第9章的末尾进行正则表达式练习题。 - 雄辩的Javascript 。 提供了测试正则表达式的功能。 当我运行此函数时,它会产生未定义的结果,而不是该函数期望的console.log输出。 码
function verify(regexp, yes, no) { // Ignore unfinished exercises if (regexp.source == "...") return; for (let str of yes) if (!regexp.test(str)) { console.log(`Failure to match '${str}'`); } for (let str of no) if (regexp.test(str)) { console.log(`Unexpected match for '${str}'`); } } // test for car and cat console.log(verify(/ca[rt]/, ["my car", "bad cats"], ["camper", "high art"]));
您有三个console.log
语句。
一个记录verify
的返回值。 您没有在该函数中放入return
语句,因此它将始终返回undefined
。
仅记录是否yes
中的内容未通过正则表达式…,但yes
数组中的所有内容均通过了它。
最后一个只有在no
通过的情况下通过日志记录,但是其中没有任何一个元素通过测试。
您在if和for循环之外缺少默认的return语句。 这应该为您提供成功的控制台日志。
function verify(regexp, yes, no) {
// Ignore unfinished exercises
if (regexp.source == "...") return;
for (let str of yes) if (!regexp.test(str)) {
console.log("Failure to match '${str}'");
}
for (let str of no) if (regexp.test(str)) {
console.log("Unexpected match for '${str}'");
}
console.log("all good!");
}
// test for car and cat
console.log(verify(/ca[rt]/,
["my car", "bad cats"],
["camper", "high art"]));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.