How to check if a given string is present in an array or list in JavaScript?

Possible duplicates:
Javascript - array.contains (obj)
Best way to find an element in a JavaScript array?

I want to check, for example, the word "the" in a list or map. Is there any built-in function for this?

+4
source share
2 answers

In javascript you have arrays (lists) and objects (maps).

Literary versions are as follows:

var mylist = [1,2,3]; // array var mymap = { car: 'porche', hp: 300, seats: 2 }; // object 

if you find out if a value exists in the array, just flip it:

 for(var i=0,len=mylist.length;i<len;i++) { if(mylist[i] == 2) { //2 exists break; } } 

if you find out if the card has a certain key or has a key with a certain value, all you have to do is access it as follows:

 if(mymap.seats !== undefined) { //the key 'seats' exists in the object } if(mymap.seats == 2) { //the key 'seats' exists in the object and has the value 2 } 
+4
source

Array.indexOf(element) returns -1 if the element is not found, otherwise returns its index

+5
source

Source: https://habr.com/ru/post/1342987/


All Articles