javascript - 使用数组防止基于值的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';
}
我可能做错了什么?
解决方案
你可以这样做
const states = [
"CA",
"IL"
];
const value = 'CA';
if (!states.includes(value)) {
console.log('does not contain');
} else {
console.log('does contain');
}
推荐阅读
- php - 将 json 响应发送回 webhook 调用者
- vb.net - 有没有一种方法可以在 Visual Basic .NET 中向选项卡添加热键,就像向按钮添加热键一样简单?
- data-science - 快感;表格的动态尺寸
- regex - 为什么 %r{ around } 我的正则表达式会破坏我的 gsub?
- reactjs - 在 ReactJS 中每 30 秒调用一次 API
- python - 使用 atan2 绘制等高线图的问题
- http - 无法在 ASP.NET Core 中调用 Web API 的 Patch 方法
- javascript - 如何在 React js 中的 div 上设置背景图像?
- python - 通过 USB-Stick 在外部“监视器”上运行 Python 动画?
- r - 在 R 中使用 `BTM` 和 `predict` 会输出 0.1 的统一主题概率