[英]Writing if-statements more concisely
在JavaScript(和大多数其他编程语言)中,我已经注意到,在检查多个条件的同一个变量并为每个条件执行相同的操作时,很难简洁地编写if语句。 在这种情况下是否可以更简洁地编写if语句?
if(x==1|x==2|x==3){ //Is there any way to make this less verbose?
console.log("X equals either 1 or 2 or 3!");
}
//this isn't syntactically correct, but it's more concise,
//and I wish it were possible to write it more like this
if(x==(1|2|3)){
console.log("X equals either 1 or 2 or 3!");
}
您可以使用正则表达式:
if (/^(1|2|3)$/.test(x)) { ... }
您可以使用此:
if ([1, 2, 3].indexOf(x) >= 0) { ... }
如果需要更复杂的相等性测试,则可以定义自己的函数,并将其与内置的some()
迭代器一起使用:
function match(value1, value2) { var result = . . .; return result; }
if ([1, 2, 3].some(match.bind(null, x))) { . . . }
( bind
出现在JS 1.8.5中;如果需要向后兼容,可以使用:
if ([1, 2, 3].some(function(elt) {return match(x, elt);})) { . . . }
根据我的经验,大多数情况下,仅通过定义返回布尔值的方法就可以使if语句更加简洁。 您可以使代码更具可读性,更易于测试,甚至您可能以这种方式重用更多代码。
当然,其他答案也很方便。
根据要求的一个例子:
if (password.length < 6 || ! /[0-9]/.test(password) || password == userName) {
alert('password doesn\'t meet security standards!');
}
与
function isSecurePassword(pw, userName) {
if (password.length < 6) return false;
if (/[0-9]/.test(password)) return false;
if (password == userName) return false;
return true;
}
if ( ! isSecurePassword(pw, userName)) {
alert(..);
}
(通常,您可能会拥有对象和方法,而不必传递变量)
是的,我经常想知道使用相同值的多个if语句的捷径。
如果您有空闲时间,我建议您探索JS的一些函数式编程构造。 您也许可以实现更优雅的解决方案。
我无法想出什么好东西或声明,但是“ AND”似乎没有任何头脑。
var Cond = {
'and': function(val, predicates) {
return predicates.every( function(predicate) { return predicate(val) } );
}
}
var predicates = [
function(val) { return val > 40; }
function(val) { return val < 45; }
function(val) { return val === 42; }
];
console.log( Cond.and( 42, predicates ) );
我的例子是超级la脚,但您应该足够轻松地玩耍。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.