我正在寻找直接的方法来检查从后端收到的 JSON 是否包含我需要的值,而不抛出异常或创建 if
语句的 for 循环。
我希望它看起来像这样:
success = function(requestBody, xhr, options){
jsonObj = JSON.parse(requestBody);
if (!json.path.to.item.is.very.deep[0].really[3]){
responseErrorHandler(requestBody, xhr, options)
}
// More Code here
}
这段代码显然不起作用,因为如果 I.E. json 对象没有 item
对象,抛出错误并且代码停止。
我可以创建一个 for
循环并解析 json,但我喜欢看到快捷方式。
最佳答案
抛出错误 - 这是一件好事,你可以处理它!将访问值的尝试(并且仅该行,以避免捕获不相关的错误)包装在 try-catch 中,例如:
try {
var x = json.path.to.item.is.very.deep[0].really[3];
} catch(e) {
// ... handle failure...
return;
}
if (typeof x !== "number") { // or whatever you need
// ... handle failure...
return;
}
// handle success
关于javascript - 检查 JSON 对象是否包含某些值的良好且快速的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28474760/