Как проверить, не равно ли значение другому значению в массиве с помощью javascript

#javascript #vue.js

Вопрос:

У меня есть объект пользователя, как показано ниже, и массив идентификаторов местоположения. Я не хочу, чтобы user.location_id был равен любому значению в массиве location_ids, указанному ниже с помощью Javascript. Пожалуйста, помогите мне достичь этого.

 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

Комментарии:

1. if (!location_ids.includes(user.location_id)) { console.log("Select user"); }

Ответ №1:

Вы можете использовать метод 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");
} 

Комментарии:

1. OP не хочет user.location_id , чтобы в массиве, поэтому вы должны отрицать includes результат.

2. Спасибо @decpk, отличная находка, приятель.

3. Лучше объяснить, как ваш ответ решил проблему ОП….

Ответ №2:

Вот [ссылка] (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>