MyTetra Share
Делитесь знаниями!
How to check if array element exists or not in javascript?
Время создания: 13.07.2018 15:30
Текстовые метки: javascript array element exists
Раздел: Javascript
Запись: Velonski/mytetra-database/master/base/1523013114alxz4mdfrp/text.html на raw.githubusercontent.com

117

down vote

favorite

15


I am working with titanium ,


my code looks like as ,


var currentData = new Array();


if(currentData[index]!==""||currentData[index]!==null||currentData[index]!=='null')

{

Ti.API.info("is exists " + currentData[index]);

return true;

}

else

{

return false;

}


I am passing index to array currentData,


For non existing element , i am still not able to detect it using above code

javascript titanium titanium-mobile

shareimprove this question

edited Oct 28 '12 at 10:09

suresh.g

2,53652053

asked Oct 28 '12 at 9:56

Pradeep

2,26732146


1

Your logic is wrong. You need conjunctions (&&) between the individual conditions. ? J. K. Oct 28 '12 at 9:59


add a comment

9 Answers

active

oldest

votes

up vote

208

down vote

accepted


Use typeof arrayName[index] === 'undefined'


i.e.


if(typeof arrayName[index] === 'undefined') {

// does not exist

}

else {

// does exist

}


shareimprove this answer

edited Feb 12 '15 at 5:56

answered Oct 28 '12 at 9:58

techfoobar

49.2k978102


3

+1, nice. You can also use if(arrayName[index] === 'undefined') as a shortcut ? AnchovyLegend Oct 8 '13 at 0:08

44

@AnchovyLegend no, you cannot! But you can use if(arrayName[index] === undefined). ? Denis V Nov 29 '13 at 15:01

10

this fails, if the item is there, but it's value is undefined; use this answer instead -> stackoverflow.com/questions/1098040/? ? Matus May 17 '14 at 21:25

as @Matus said, there is more explanation here, you should be aware on. ? S.Thiongane Aug 8 '14 at 8:47


add a comment

up vote

59

down vote


var myArray = ["Banana", "Orange", "Apple", "Mango"];


if (myArray.indexOf(searchTerm) === -1) {

console.log("element doesn't exist");

}

else {

console.log("element found");

}


shareimprove this answer

edited May 8 '17 at 8:12

Pere

66211441

answered Sep 12 '13 at 17:35

yeswanth

1,043716


2

Unfortunately, this one doesn't work in IE 7 and below. ? darksoulsong Oct 7 '14 at 15:21

2

This in my opinion is the best answer, by now IE 7 is not mainteined any more so it's not a problem. Although I will suggest to use the triple equals if(myArray.indexOf(searchTerm) === -1) ? Mauro Gava Sep 1 '16 at 2:49


add a comment

up vote

3

down vote


Consider the array a:


var a ={'name1':1, 'name2':2}


If you want to check if 'name1' exists in a, simply test it with in:


if('name1' in a){

console.log('name1 exists in a')

}else

console.log('name1 is not in a')


shareimprove this answer

answered Aug 16 '15 at 4:43

Amir

14515


3

"var a" is not an array object in your case, but a regular object. Should be var a = [ ... ]. I think this is what author needed. ? tomazahlin Dec 16 '15 at 13:10

This is how to check for the existence of a key in an object, not the presence of an index in an array. ? Beejamin Feb 2 '17 at 0:58


add a comment

up vote

3

down vote


This way is easiest one in my opinion.


var nameList = new Array('item1','item2','item3','item4');


// Using for loop to loop through each item to check if item exist.


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

if (nameList[i] === 'item1')

{

alert('Value exist');

}else{

alert('Value doesn't exist');

}


And Maybe Another way to do it is.


nameList.forEach(function(ItemList)

{

if(ItemList.name == 'item1')

{

alert('Item Exist');

}

}


shareimprove this answer

edited Dec 31 '15 at 23:18

answered Dec 31 '15 at 23:07

AmJustSam

1648

add a comment

up vote

2

down vote


I had to wrap techfoobar's answer in a try..catch block, like so:


try {

if(typeof arrayName[index] == 'undefined') {

// does not exist

}

else {

// does exist

}

}

catch (error){ /* ignore */ }


...that's how it worked in chrome, anyway (otherwise, the code stopped with an error).

shareimprove this answer

answered Aug 9 '13 at 14:00

Swiss Mister

1,46311127

add a comment

up vote

2

down vote


If elements of array are also simple objects or arrays, you can use some function:


// search object

var element = { item:'book', title:'javasrcipt'};


[{ item:'handbook', title:'c++'}, { item:'book', title:'javasrcipt'}].some(function(el){

if( el.item === element.item && el.title === element.title ){

return true;

}

});


[['handbook', 'c++'], ['book', 'javasrcipt']].some(function(el){

if(el[0] == element.item && el[1] == element.title){

return true;

}

});


shareimprove this answer

edited Jan 23 '15 at 11:25

answered Jan 22 '15 at 12:42

Yaroslav Fedoruk

10623

add a comment

up vote

2

down vote


you can simply use this:


var tmp = ['a', 'b'];

index = 3 ;

if( tmp[index]){

console.log(tmp[index] + '\n');

}else{

console.log(' does not exist');

}


shareimprove this answer

answered Jul 21 '15 at 15:23

Salar

2,2321831

add a comment

up vote

2

down vote


Simple way to check item exist or not


Array.prototype.contains = function(obj) {

var i = this.length;

while (i--)

if (this[i] == obj)

return true;

return false;

}


var myArray= ["Banana", "Orange", "Apple", "Mango"];


myArray.contains("Apple")


shareimprove this answer

answered Nov 23 '16 at 14:21

Suhail Ahmed

713

add a comment

up vote

1

down vote


If you use underscore.js then these type of null and undefined check are hidden by the library.


So your code will look like this -


var currentData = new Array();


if (_.isEmpty(currentData)) return false;


Ti.API.info("is exists " + currentData[index]);


return true;


It looks much more readable now.


Так же в этом разделе:
 
MyTetra Share v.0.59
Яндекс индекс цитирования