简体   繁体   中英

How can I check if key in array exist without error code?

I made this variable "generateError" to not work on purpose but I encounter this same issue in another context when checking for keys in an array. So my question, how do I get the variable status to just show "array not working" instead of generating error code?

 var numbers = [1, 2, 3, 4]; var generateError = numbers['badKey'][2]; if (typeof(generateError)==undefined){ var status=("array not working"); } else { var status=("array is working"); } document.getElementById("status").innerHTML=status;
 <div id="status"></div>

var numbers = [1, 2, 3, 4];
var generateError = numbers['badKey'][2];
var status;
if (typeof(generateError)=='undefined'){
  status=("array not working");
} else {
  status=("array is working");
}

document.getElementById("status").innerHTML=status;

Try this and read this page its help you in future.

Side Info - typeof method will return a string so when using it try it like this

if(typeof generateError == 'undefined')

You could make use of the try/catch methods. it will try to run everything in the try block and if theres an error the catch block will catch the error and do whatever you want with it.

var numbers = [1, 2, 3, 4];
var status;

try{
    var tryToGetIndex = numbers['badKey'][2];
    status = tryToGetIndex;
}
catch(error){
    status="array is not working";
}

document.getElementById("status").innerHTML=status;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM