I am working with Titanium, my code looks like this:
var currentData = new Array();
if(currentData[index]!==\"\"||currentData[index]!==null||currentData[ind
const arr = []
typeof arr[0] // "undefined"
arr[0] // undefined
If boolean expression
typeof arr[0] !== typeof undefined
is true then 0 is contained in arr
If you are looking for some thing like this.
Here is the following snippetr
var demoArray = ['A','B','C','D'];
var ArrayIndexValue = 2;
if(demoArray.includes(ArrayIndexValue)){
alert("value exists");
//Array index exists
}else{
alert("does not exist");
//Array Index does not Exists
}
var myArray = ["Banana", "Orange", "Apple", "Mango"];
if (myArray.indexOf(searchTerm) === -1) {
console.log("element doesn't exist");
}
else {
console.log("element found");
}
When trying to find out if an array index exists in JS, the easiest and shortest way to do it is through double negation.
let a = [];
a[1] = 'foo';
console.log(!!a[0]) // false
console.log(!!a[1]) // true
Someone please correct me if i'm wrong, but AFAIK the following is true:
hasOwnProperty
"inherited" from Object
hasOwnProperty
can check if anything exists at an array index.So, as long as the above is true, you can simply:
const arrayHasIndex = (array, index) => Array.isArray(array) && array.hasOwnProperty(index);
usage:
arrayHasIndex([1,2,3,4],4);
outputs: false
arrayHasIndex([1,2,3,4],2);
outputs: true
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).