Home javascript JavaScript Array Search

JavaScript Array Search

Author

Date

Category

I have a JS array containing numeric values:

var massiv = [
  "100", "101", "456", "1000", "321"
]

And there is a variable:

var peremennaya = "101"

Task:
if the variable matches one of the values ​​of the array, then you need to perform an action. For example:

alert = "Found 101"

The array contains only numeric values, but they are wrapped in quotes for universality, as it seems to me, i.e. so that the script does not only compare values ​​

==

but also found literal matches.

If possible, I would like to see an example with explanations of each step in the form of comments or as convenient.


Answer 1, authority 100%

Using the for

loop as an example

var massiv = [
  "100", "101", "456", "1000", "321"
]
var peremennaya = "101";
for (i = 0; i & lt; massiv.length; i ++) {
if (peremennaya == massiv [i]) {
alert ("We found" + massiv [i])
}
} 

Answer 2, authority 98%

var peremennaya = 101;
var massiv = [
  100, 101, 456, 1000, 321
];
if (massiv.indexOf (peremennaya)! = -1)
 console.log ('Array contains value' + peremennaya); 

Answer 3, authority 50%

Orthodox js has a special search function by criterion
and if there will be multiple occurrences of an element in the array

var peremennaya = 101;
var massiv = [100, 101, 456, 1000, 321];
var itog = massiv.filter (item = & gt; {
 return item === peremennaya; // comparison logic here
});
console.log (itog); 

Answer 4

You can with Array.prototype.includes () :

var testArray = [
  "100", "101", "456", "1000", "321"
]
var valueToFind = "101";
testArray.includes (valueToFind)? console.log ("find:" + valueToFind): console.log ("we didn't find anything")

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions