简体   繁体   English

如何检查数组中的键是否存在而没有错误代码?

[英]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.我故意使这个变量“generateError”不起作用,但是在检查数组中的键时,我在另一个上下文中遇到了同样的问题。 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 Side Info - typeof 方法将返回一个字符串,因此在使用它时尝试这样

if(typeof generateError == 'undefined')

You could make use of the try/catch methods.您可以使用 try/catch 方法。 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.它将尝试运行 try 块中的所有内容,如果出现错误,catch 块将捕获错误并执行您想要的任何操作。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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