我有一个如下所示的用户对象和一个位置id数组。我不希望user.location_id等于如下使用Javascript所述的location_id数组中的任何值。请帮我实现它。
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");
}
这里有[链接](https://techfunda.com/howto/729/not-equal-operator)
这是[链接](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>