How can I register ArrayIndex regardless of JavaScript?

I have an array var john = ['asas','gggg','ggg'];

If I access john at index 3, i.e. john[3] , he fails.

How can I display a message or warning that there is no value in this index?

+8
javascript logging
source share
6 answers
 function checkIndex(arrayVal, index){ if(arrayVal[index] == undefined){ alert('index '+index+' is undefined!'); return false; } return true; } 

 //use it like so: if(checkIndex(john, 3)) {/*index exists and do something with it*/} else {/*index DOES NOT EXIST*/} 
+6
source share
 if (typeof yourArray[undefinedIndex] === "undefined") { // It undefined console.log("Undefined index: " + undefinedIndex; } 
+6
source share

Javascript tried to catch

 try { //your code } catch(err) { //handle the error - err i think also has an exact message in it. alert("Error"); } 
+2
source share

Javascript arrays start at 0. so your array contains the contents 0 - 'asas', 1 - 'gggg', 2 ​​- 'ggg'.

+1
source share
 var john = ['asas','gggg','ggg']; var index=3; if (john[index] != undefined ){ console.log(john[index]); } 
+1
source share

Arrays are indexed starting at 0, not 1.

There are 3 elements in the array; they are:

 john[0] // asas john[1] // gggg john[2] // ggg 
0
source share

All Articles