我有一个if循环来检查一些参数:
if (num1!=0 && A0=="check" && A1!="check" && A2!="check"...)
{}
现在问题是A1转到A1000
唯一的解决方案是编写A0 ==“ check” && A1!=“ check” && A2!=“ check”。...
任何更智能的解决方案?
答案 0 :(得分:1)
通常,拥有如此多的枚举变量似乎是一个坏习惯。
最好将object
或array
称为A
并将所有条件放入该实体。
例如:
var A = [];
A.push('foo');
A.push('ololo');
A.push('check');
// Now if we want to check if there is some value, we can simply do somethink like this
if (A.find(_ => _ === 'check')) {
console.log ('Some condition is "check"')
}
if (!A.find(_ => _ === 'ururu')) {
console.log ('There is no "ururu" condition')
}
将来,当代码库和项目将增长时,与array
或object
一起使用也将更好。
答案 1 :(得分:0)
我不确定您是在谈论函数参数的for循环还是在if语句中检查一堆变量。因此,我为您提供两种解决方案。
var A0 = 'check';
var A1 = 'foo';
var A2 = 'foo';
var A3 = 'foo';
var A4 = 'foo';
var A5 = 'foo';
var A6 = 'foo';
var A7 = 'foo';
var A8 = 'foo';
var A9 = 'foo';
var allCheck = true;
if (A0 === 'check') {
for (i = 1; i <= 9; i++) {
if(['A' + i] !== 'check') {
allCheck = false;
console.log(`A${i} is not check`);
}
}
}
if (allCheck) {
// Do something here
}
function foo (A0, A1, A2, A3, A4, A5, A6, A7, A8, A9) {
for (name in arguments) {
if(arguments[name] === 'check') {
console.log('dont use check');
} else {
console.log('looks good');
}
}
}
foo('check', 'foo', 'foo', 'foo', 'foo', 'foo', 'foo', 'foo', 'foo', 'foo');
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
答案 2 :(得分:0)
假设您正在比较字符串。
const assumptions = ['a', 'b', 'c'];
const assertions = ['a', 'b', 'c', 'd'];
let result;
// Using Reduce
result = assumptions.reduce((accumulator, actual, index) => {
// Remember that false AND something is false
// Note: here you cannot break the loop, it will run to completion
return accumulator && actual === assertions[index];
}, true);
// Using Loop
result = true;
for (let i = 0; i < assumptions.length; i++) {
result = result && (assumptions[i] === assertions[i]);
// Once it gets to false it will never get to true again
if (!result) {
break;
}
}
注意:断言可以是您将假设作为参数调用的函数数组。