[英]Index.js:46 Uncaught TypeError: Cannot Read Property 'lifestyle' Of Undefined
I am new to jquery, I am writing an ajax call to retrieve data from an API,我是 jquery 的新手,我正在编写一个 ajax 调用来从 API 检索数据,
the function is been used on both live and local,该功能用于现场和本地,
On my local the response comes as在我的本地,响应是
var response = res;
var test = response.hearts.assessments.lifestyle
on my live, the response comes as在我的直播中,回应是
var response = res;
var test = response.assessments.lifestyle
it comes without [heart]它没有[心脏]
I need to implement a condition to work with both condition我需要实现一个条件来处理这两个条件
currently, I have used an if-else condition but it gives an error of undefined lifestyle on my local.目前,我使用了 if-else 条件,但它在我的本地给出了未定义生活方式的错误。
this is my code这是我的代码
var response = res;
if(typeof(response.assessments.lifestyle) != "undefined" || response.assessments.lifestyle !== null) {
var lifestyle = response.assessments.lifestyle;
}
else{
var lifestyle = response.hearts.assessments.lifestyle;
}
But this code won't work, can someone please help Thank you..但是这段代码不起作用,有人可以帮忙吗谢谢..
Try as given按规定尝试
let response = response.assessments || response.hearts.assessments || [];
response = response.lifestyle ||"";
if "response.assessments" comes undefined it will check "response.hearts.assessments", If both comes undefined or empty or undefined it will return empty array second line to check lifestyle property, If it is undefined than blank string如果“response.assessments”未定义,它将检查“response.hearts.assessments”,如果两者都未定义或为空或未定义,它将返回空数组第二行以检查生活方式属性,如果未定义则为空字符串
You should check that the key "hearts" exists in response.assessments with this method您应该使用此方法检查 response.assessments 中是否存在关键的“hearts”
var response = res;
if("hearts" in response) {
var lifestyle = response.hearts.assessments.lifestyle;
} else {
var lifestyle = response.assessments.lifestyle;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.