Javascript if语句中的多个条件

麦卡法尔

这是一个令人尴尬的基本问题,但我找不到MDN,W3schools,此处或Google搜索上的答案。

当引用多个条件时,例如在if语句中:

if ((a != b) && (a != c) && (a != d)){...}

(考虑到列表可以多长时间),必须有一种更有效的方法。我想它看起来像这样:

if (a != (b || c || d)){...}

那是行不通的,但是必须有其他有效的解决方案。如果可以的话让我知道。谢谢。

编辑:显然有价值的信息:所有变量都是基元。

丹吉格

您可以Array使用所有可能的值创建一个,并使用Array.prototype.indexOf()Array.prototype.includes()检查一个Give值是否在其中Array

const values = [1, 2, 3, 4, 5, 7, 8, 9];

console.log(`[${ values.join(', ') }].indexOf(1) = ${ values.indexOf(1) }`);
console.log(`[${ values.join(', ') }].indexOf(6) = ${ values.indexOf(6) }`);
console.log(`[${ values.join(', ') }].includes(1) = ${ values.includes(1) }`);
console.log(`[${ values.join(', ') }].includes(6) = ${ values.includes(6) }`);

如您所见,如果该值不在或其第一次出现的索引中indexOf()则将返回,这可能取决于您的用例,而在该值存在或其他情况下才返回,并且IE不支持。-1Arrayincludes()truefalse

因此,在您的情况下,您将得到如下所示的结果:

const b = 'b';
const c = 'c';
const d = 'd';

const values = [b, c, d];

let target = 'a';

if (!values.includes(target)){
  console.log(`${ target } not in [${ values.join(', ') }]`);
}

target = 'b';

if (values.includes('b')){
  console.log(`${ target } in [${ values.join(', ') }]`);
}

// You could also do [b, c, d].includes(target) if you don't need to reuse that Array.

这将适用于原始值,例如stringnumberbooleannullundefinedsymbol还可以使用Objectreference,不要与just混淆,Object如下所示:

const values = [{ foo: 1 }, { bar: 2 }, { baz: 3 }];
const target = { foo: 1 };

console.log(`values.includes(target) = ${ values.includes(target) }`);

// This will not work because the { foo: 1 } object inside values and the one we are passing to
// includes are not the same, as you can see here:

console.log(`values[0] === target = ${ values[0] === target }`);

// However, if we get a reference to it, then those two references can be compared successfully:

const reference = values[0];

console.log(`values[0] === reference = ${ values[0] === reference }`);

// So now we can also use includes or indexOf:

console.log(`values.includes(reference) = ${ values.includes(reference) }`);

如果你想了解它是如何工作,你可以尝试实现类似的功能indexOfincludes你自己。很简单的东西:

function isValueInArray(arr, value) {

  const size = arr.length;
  
  // Iterate over all the indexes in arr:
  for (let i = 0; i < size; ++i) {
  
    // Check whether the value at the current index matches the target value:
    if (arr[i] === value) {
    
      // If so, we have found value at index i in arr, so we return true and stop searching:
      return true;
      
      // Note we could also return the index if we care about the position the value is at.
    }
  }
  
  // We have checked all the values in arr and none of them matched, so we return false: 
  return false;
}

const values = [0, 1, 2, 3, 4, 5, 7, 8, 9];

console.log(`isValueInArray(values, 1) = ${ isValueInArray(values, 1) }`);
console.log(`isValueInArray(values, 6) = ${ isValueInArray(values, 6) }`);

但是,请记住,实际的实现稍微复杂一些。例如,您可以查看此polyfillincludes

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章