Compare elements of an arrangement

4

How can I compare a variable with each and every element of an array

var saludo = ["hi", "hola", "buenos dias", "buen dia"];
if(otraVariableX == saludo[]) { 
    alert("Hola!!!"); 
}

only the if works for me if I specify the positions of the example array:

saludo[0]
saludo[1]

But I want it to be compared with all the elements of the arrangement, 4 in this case greeting [0-3]

    
asked by matteo 02.05.2017 в 21:51
source

4 answers

3

You can use a for to go through the whole arrangement and go comparing.

 saludo =["hi", "hola", "buenos dias", "buen dia"];
 otraVariableX = "hola";

for (var i = 0; i < saludo.length; i++) {

  if (otraVariableX == saludo[i]) {
    alert("Hola!!!");
  }
}
    
answered by 02.05.2017 / 21:57
source
3

The Arrays have in a method includes () , to know if an element is contained in a Array , it will return a value booleano , TRUE if it is the opposite case FALSE .

var saludo = ["hi", "hola", "buenos dias", "buen dia"];

if(saludo.includes("hola"))
  console.log("Si se encuentra");
else
  console.log("No Se encuentra ");
    
answered by 02.05.2017 в 21:56
2

Here are some ways to verify your doubt:

saludo.some(function(el){  return el === "hola"}); // si alguno cumple esta condición 
//output = true

saludo.includes("hola");  //true o false si existe o no
//output = true

saludo.indexOf("hola"); // si es mayor a -1 existe y retorna su posición 
//output = 1

var res = false; 
saludo.forEach(function(el){
   if(el === "hola") res = true;    
});

console.log(res); //output = true 
    
answered by 02.05.2017 в 22:22
1

One way can be to traverse the arrays with for..in , or with the join () method, in The following example shows you the 2 ways (among others):

var saludo = ["hi", "hola", "buenos dias", "buen dia"];
var otraVariableX = prompt("ingresa un saludo");

// Ejemplo con: for..in
for (n in saludo) {
 if (otraVariableX == saludo[n]) {
  alert("Hola!!! for..in");
 }
}
// Ejemplo con: el método join()
if (saludo.join(" ").indexOf(otraVariableX)+1) {
 alert("Hola!!! join()");
}
    
answered by 02.05.2017 в 22:16