Javascript condense if statement

Javascript condense if statement

本文关键字:statement if condense Javascript      更新时间:2023-09-26

我在javascript中有一个if语句,它是

if(prop < 0 || trans < 0 || queue < 0 || proc < 0 
    || prop > 1 || trans > 1 || queue > 1 || proc > 1 
    || prop == "" || trans == "" || queue == "" || proc == ""){

有没有办法压缩它?对于proptransqueueproc。如果值不介于 0 和 1 之间,或者如果它有一个空字符串值,我想创建一个 if 语句

建立在乔丹的答案之上:

var checkThese = [prop, trans, queue, proc];
var result = checkTruthinessOf(checkThese);
function checkTruthinessOf(things) {
    return things.every(function(el) {
       return (el < 0 || el > 1 || el === "");
    });
}

请参阅Array.prototype.every()

var checkThese = [prop, trans, queue, proc];
var result = checkTruthinessOf(checkThese);
function checkTruthinessOf(things) {
    var returnValue = false;
    [].forEach.call(things, function(thing){
       if (thing < 0 || thing > 1 || thing == "") returnValue = true;
    });
    return returnValue;
};

我从jQuery中学会了这个练习。它消除了额外的数组,只需传入任意数量的参数。然后使用溜冰场的功能一次验证所有内容。

var result = checkTruthinessOf(prop, trans, queue, proc);
function checkTruthinessOf(/*unlimited arguments*/) {
   return Array.prototype.every.call(arguments, function(thing) {
       return (thing < 0 || thing > 1 || thing === "");
    });
}