简体   繁体   English

如何使用 javascript 检查一个值是否不等于数组中的另一个值

[英]How to check if a value is not equal to another value in the array using javascript

I have a user object as below and an array of location ids.我有一个用户 object 和一个位置 ID 数组。 I don't want the user.location_id to be equal to any value in the location_ids array stated as below using Javascript.我不希望 user.location_id 等于 location_ids 数组中的任何值,如下所述,使用 Javascript。 Please help me achieve it.请帮助我实现它。

user: {
  first_name: 'James',
  last_name: 'Smith',
  location_id: 21
},

location_ids:[23, 31, 16, 11]

So I want to所以我想

if (user.location_id != any value in the locations_ids array) {
 console.log("Select User")
}

Help me achieve this using javascript使用 javascript 帮助我实现这一目标

You can use the includes method to find if the element is present in the array or not.您可以使用includes方法来查找元素是否存在于数组中。

The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate. includes() 方法确定数组是否在其条目中包含某个值,并根据需要返回 true 或 false。 - MDN -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"); }

Here's [a link] ( https://techfunda.com/howto/729/not-equal-operator )这是[链接]( https://techfunda.com/howto/729/not-equal-operator

Here's [a link] ( https://techfunda.com/howto/929/array-indexof-search )这是[链接]( https://techfunda.com/howto/929/array-indexof-search

 function myFunction() { var a = ["France", "Nritian", "Israel", "Bhutan", "US", "UK"]; var b = a.indexOf("Africa"); document.getElementById("myId").innerHTML = b; }
 <.DOCTYPE html> <html> <head> <title>Demo</title> </head> <body> <p>Click the below button to know the output for an search which is not presented in an array,</p> <input type="button", onclick="myFunction()" value="Find"/> <p id="myId"></p> </body> </html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM