首页 > 解决方案 > 使用数组防止基于值的if语句

问题描述

因此,下面的代码在执行之前检查一个值是否具有“CA”,如下所示:

if (this.value !== 'CA') {
    formStatePick.style.display = 'block';
    document.querySelector('#stateWarning b#stateName').textContent = this.options[this.selectedIndex].text;
} else {
    formStatePick.style.display = 'none';
}

我希望能够放入一个名为 states 的数组,然后使用数组值来检查它是否不相等。

这是我的尝试,但它不起作用:

var States = [
    "CA",
    "IL",
];

if (this.value !== States) {
    formStatePick.style.display = 'block';
    document.querySelector('#stateWarning b#stateName').textContent = this.options[this.selectedIndex].text;
} else {
    formStatePick.style.display = 'none';
}

我可能做错了什么?

标签: javascript

解决方案


你可以这样做

const states = [
  "CA",
  "IL"
];

const value = 'CA';


if (!states.includes(value)) {
  console.log('does not contain');
} else {
  console.log('does contain');
}


推荐阅读