javascript - 如何使用javascript检查一个值是否不等于数组中的另一个值
问题描述
我有一个如下的用户对象和一个位置 ID 数组。我不希望 user.location_id 等于使用 Javascript 如下所述的 location_ids 数组中的任何值。请帮助我实现它。
user: {
first_name: 'James',
last_name: 'Smith',
location_id: 21
},
location_ids:[23, 31, 16, 11]
所以我想
if (user.location_id != any value in the locations_ids array) {
console.log("Select User")
}
帮助我使用 javascript 实现这一目标
解决方案
您可以使用includes方法来查找元素是否存在于数组中。
includes() 方法确定数组是否在其条目中包含某个值,并根据需要返回 true 或 false。-MDN
if(!location_ids.includes(user.location_id)){}
const user = {
first_name: "James",
last_name: "Smith",
location_id: 21,
};
const location_ids = [23, 31, 16, 11];
if (!location_ids.includes(user.location_id)) {
console.log("Select user");
}
// Change location ID
user.location_id = 11;
if (!location_ids.includes(user.location_id)) {
console.log("Select user");
} else {
console.log("Don't select user");
}
推荐阅读
- magento2 - 管理面板中没有显示图像,也没有退出选项。
- java - 设置 SlidingPaneLayout 水平滚动禁用
- python - Pandas 数据框 read_excel 不将左上角空白单元格视为列?
- c# - 从 SSIS 包通过 HTTP 下载文件不起作用
- python - Python 错误 - “ImportError: No module named”
- ios - Xcode 模拟器开启。由于音频引擎,Jenkins space 导致自动化测试崩溃
- excel - 在工作簿打开事件中启用宏
- actions-on-google - 在没有 Dialogflow 的情况下在 google 上发布操作
- java - Spring执行器shutdown-endpoint无法停止java进程
- r - as.Date 在西班牙语言环境中带有点的缩写月份 (%b)