How to check if array element exists or not in javascript?
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
Use typeof arrayName[index] === 'undefined'
ie
if(typeof arrayName[index] === 'undefined') {
// does not exist
}
else {
// does exist
}
var myArray = ["Banana", "Orange", "Apple", "Mango"];
if (myArray.indexOf(searchTerm) === -1) {
console.log("element doesn't exist");
}
else {
console.log("element found");
}
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')
链接地址: http://www.djcxy.com/p/26642.html
上一篇: 检查一个JS对象中是否存在一个键