首页 > 解决方案 > 如何使用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 实现这一目标

标签: javascriptvue.js

解决方案


您可以使用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");
}


推荐阅读