我正在尝试将我的 if
语句管理为 switch
语句以评估正则表达式,但我不知道该怎么做。我尝试了很多可能性,但做不到。看下面的代码,对吗?:
var username = $('input.username'),
phone = $('input.phone'),
numRegex = /^[0-9]/i,
alphaRegex = /^[a-zA-Z]/i,
usernameVal = username.val(),
phoneVal = phone.val();
switch (phoneVal) {
case numRegex.test(phoneVal):
console.log('Only digits please.');
break;
default:
console.log('It\'s all good.');
}
非常感谢。
最佳答案
我认为这种做法违背了 switch
语句在 case
语句中具有条件的要点。它的目的是在给定单个输入的情况下测试多个输出。
如果 JavaScript 在 switch..case
中支持多个输入(或数组的 destructuring),我可能会看到类似这样的内容:
switch (numRegex.test(phoneVal), alphaRegex.test(usernameVal)) {
case false, false:
console.log('Neither are valid.');
break;
case true, false:
console.log('Invalid username.');
break;
/* snip */
default:
console.log('All\'s good.');
}
但是,唉,在这种情况下,我会说坚持使用 if..else
是一个更好、更容易遵循/理解的选项:
if (numRegex.test(phoneVal)) {
console.log('Only digits please.');
return false;
} else if (alphaRegex.test(usernameVal)) {
console.log('Only alpha-numeric please.');
return false;
} else {
console.log('It\'s all good.');
return true;
}
关于javascript - 使用 switch 语句评估 javascript 中的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7893567/