这是一个令人尴尬的基本问题,但我找不到MDN,W3schools,此处或Google搜索上的答案。
在引用多个条件时,例如在if语句中:
if ((a != b) && (a != c) && (a != d)){...}
(考虑到列表可以多久地变长),必须有一种更有效的方法。我想它看起来像这样:
if (a != (b || c || d)){...}
那是行不通的,但是必须有其他有效的解决方案。如果可以的话让我知道。谢谢。
编辑:显然有价值的信息:所有变量都是基元。
答案 0 :(得分:4)
您可以使用所有可能的值创建一个Array
,然后使用Array.prototype.indexOf()
或Array.prototype.includes()
来检查给定值是否在该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()
或其首次出现的索引之内,则-1
将返回Array
,这可能取决于您的用例,而includes()
仅在存在该值时返回true
,否则返回false
,并且IE不支持该值。
因此,在您的情况下,您将得到如下所示的结果:
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.
这将与primitive values一起使用,因此string,number,boolean,null,undefined和symbol 也可以使用Object
references,不要与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) }`);
如果您想了解其工作原理,则可以尝试自己实现类似于indexOf
或includes
的功能。简单的东西:
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) }`);
但是,请记住,实际的实现要稍微复杂一些。例如,您可以看看this polyfill for includes
。