简体   繁体   English

如果不是,则为javascript(否则为否)

[英]javascript if if else (not else if)

I have a simple bit of code that checks some conditions, and I want each condition to cause a unique output, but if no conditions are met then to cause another unique output. 我有一段简单的代码可以检查某些条件,并且我希望每个条件都导致唯一的输出,但是如果不满足任何条件,则导致另一个唯一的输出。

Is there any way to create an else that is only triggered if all previous if statements fail? 有什么方法可以创建仅在所有先前的if语句失败时才触发的else I am aware that the below code carries out the same purpose, but it seems cumbersome and it would be nicer to have a quicker way of checking all of the variables than copy and paste all of them into another if statement. 我知道下面的代码实现了相同的目的,但是看起来很麻烦,并且比将所有变量都复制并粘贴到另一个if语句中有更快的方法来检查所有变量会更好。

 var boolean1 = true, boolean2 = true, boolean3 = false; if (boolean1) { alert("boolean1"); } if (boolean2) { alert("boolean2"); } if (boolean3) { alert("boolean3"); } /* and so on */ if (!boolean1 && !boolean2 && !boolean3 /* etc */ ) { alert("none"); } 

The only other way I can see to do this is for each function to set a different boolean and then test that. 我可以看到的唯一其他方法是为每个函数设置一个不同的布尔值,然后对其进行测试。

var boolean1 = true,
    boolean2 = true,
    boolean3 = false,
    any = false;


if (boolean1) {
  alert("boolean1");
  any = true;
}
if (boolean2) {
  alert("boolean2");
  any = true;
}
if (boolean3) {
  alert("boolean3");
  any = true;
}
/* and so on */
if (!any) {
  alert("none")
}

This probably isn't much of an improvement though. 不过,这可能不是很大的改进。

if an array is possible try this: 如果可以使用数组,请尝试以下操作:

 var booleans = [false, false, false]; var i = 0; while (i < booleans.length) { if (booleans[i] === true) { alert("boolean"+i); } i++; } i = 0; while (booleans[i] === false && i < booleans.length) { i++; } if (i == booleans.length) { alert('none'); } // Filter would work like this: var bools = booleans.filter(function (val, ind) { return !val; }); if (bools.length > 0) alert('none'); 

You can read more about filter() here: https://msdn.microsoft.com/de-de/library/ff679973(v=vs.94).aspx 您可以在此处阅读有关filter()的更多信息: https : //msdn.microsoft.com/de-de/library/ff679973 ( v=vs.94 ) .aspx

Other possibilities are using .every() as @Bergi mentioned. 其他可能性是使用.every()作为@Bergi提到的。

To make this scale, you will need to change your data structure to something you can iterate over. 为了达到这种规模,您将需要将数据结构更改为可以迭代的结构。 That way your processing logic remains the same and you can supply any size input. 这样,您的处理逻辑将保持不变,并且您可以提供任何大小的输入。 Here's one implementation where I use an object with properties representation your Boolean values. 这是一个实现,其中我使用一个对象,该对象的属性表示您的布尔值。 The checkResults function below iterates over the property names in the object, checks the value for each one, and performs an alert and sets a flag if any value is true . 下面的checkResults函数遍历对象中的属性名称,检查每个属性的值,并执行警报并设置标志(如果任何值为true At the end it checks if any value was true and alerts with that case. 最后,它检查是否有任何true值,并在这种情况下发出警报。

 function checkResults(resultMap) { var any = false; Object.keys(resultMap).forEach(function(key) { if (resultMap[key] === true) { any = true; alert(key); } }); if (!any) alert('none'); } checkResults({ 'boolean1': false, 'boolean2': true, 'boolean3': false }); 

You can build your input object property by property if you have to: 如果需要,可以按属性构建输入对象属性:

var results = {};
results['boolean1'] = true;
results['boolean2'] = false;
...
checkResults(results);

And the checkResults function always stays the same. 并且checkResults函数始终保持不变。

var accumulated = false;

acumulated = acumulated || boolean1;
if (boolean1) {
  alert("boolean1");
}

acumulated = acumulated || boolean2;
if (boolean2) {
  alert("boolean2");
}

acumulated = acumulated || boolean3;
if (boolean3) {
  alert("boolean3");
}

if(!acumulated) {
  alert("none");
}

This is not super readable but this would work: 这不是超级可读的,但这可以工作:

 var boolean1 = true, boolean2 = true, boolean3 = false; [(boolean1 && !alert("boolean1")), (boolean2 && !alert("boolean2")), (boolean3 && !alert("boolean3"))] .some(function(passed) { return passed; }) || alert("none"); 

You could maintain a flag which when passes the condition alerts none 您可以维护一个标志,该标志在通过条件时none发出警报

var boolean1 = true;
var boolean2 = true;
var boolean3 = false;
var allConditionFailed = true;

if (boolean1) {
  alert("boolean1");
  allConditionFailed = false;
}
if (boolean2) {
  alert("boolean2");
  allConditionFailed = false;
}
if (boolean3) {
  alert("boolean3");
  allConditionFailed = false;
}

if(allConditionFailed) {
   alert("none");
}

No, there is none. 不,没有。 Just imagine the control flow diagram for your code, there's no way to convert that to a structured program (or even an unstructured one) without evaluating a boolean in multiple places or without introducing helper variables. 只需想象一下代码的控制流程图,就无法将其转换为结构化程序 (甚至是非结构化程序 ),而无需在多个位置评估布尔值或不引入辅助变量。

If you want to check every condition only once (in the execution I mean, not in the code), you could do 如果您只想检查每个条件一次(在执行中,不是在代码中),则可以执行

if (boolean1) {
  alert("boolean1");
  if (boolean2) {
    alert("boolean2");
  }
  if (boolean3) {
    alert("boolean3");
  }
} else {
  if (boolean2) {
    alert("boolean2");
    if (boolean3) {
      alert("boolean3");
    }
  } else {
    if (boolean3) {
      alert("boolean3");
    } else {
      alert("none")
    }
  }
}

but that is arguably much uglier than your original solution. 但这可以说比原始解决方案难看得多。

I suspect what you actually want is an array of options: 我怀疑您真正想要的是一系列选项:

var booleans = [true, true, false];
var alerts = ["boolean1", "boolean2", "boolean3"];
for (var i=0; i<booleans.length; i++)
  if (booleans[i])
    alert(alerts[i]);
if (booleans.every(b => !b))
  alert("none");

you can use a for loop to reduce the size of the code. 您可以使用for循环来减少代码的大小。

var boolean1 = true,
  boolean2 = true,
  boolean3 = false;
  none=true;
for(i=1;i<4;i++){
    var variable=window["boolean"+i];
    if (variable) {
      alert("boolean"+i);
      none=false;
    }
}

if (none) {
  alert("none");
}

If you can save them as an array then you can use array.indexOf() to make sure that true doesn't exist in the array (all tests fail), and if it does loop through the array with array.forEach() to do something with each of them. 如果您可以将它们另存为数组,则可以使用array.indexOf()来确保数组中不存在true(所有测试均失败),并且可以通过array.forEach()遍历该数组来与他们每个人做点事。

So your code will look something like this: 因此,您的代码将如下所示:

// The array of conditions.
var bools = [true, true, false];

// Check if none of them are true (all fail).
if (bools.indexOf(true) === -1) {
    alert("none");
} else {
// Loop over them and do something based if the current one is true.
bools.forEach(function(b, i) {
    b ? alert("boolean" + (i + 1)) : '';
});
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM