Joh*_*per 9 javascript logging
我有阵列 var john = ['asas','gggg','ggg'];
如果我john
在索引3处访问,即.john[3]
, 它失败.
如何显示消息或警告,说明该索引没有值?
if (typeof yourArray[undefinedIndex] === "undefined") {
// It's undefined
console.log("Undefined index: " + undefinedIndex;
}
Run Code Online (Sandbox Code Playgroud)
function checkIndex(arrayVal, index){
if(arrayVal[index] == undefined){
alert('index '+index+' is undefined!');
return false;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
//use it like so:
if(checkIndex(john, 3)) {/*index exists and do something with it*/}
else {/*index DOES NOT EXIST*/}
Run Code Online (Sandbox Code Playgroud)