[英]How do I catch this error for an undefined property of an object?
I have a search method that utilized an API and returns a list of matches along with properties such as 'id' and 'title' but only some of these have a title.我有一个使用 API 的搜索方法,并返回匹配列表以及诸如“id”和“title”之类的属性,但只有其中一些具有标题。 When there is no title present, I get an error of undefined.
当没有标题存在时,我会收到未定义的错误。
I have tried plenty of if = undefined variations but everything comes back with this error:我已经尝试了很多 if = undefined 变化,但一切都出现了这个错误:
Cannot read property 'title' of undefined
无法读取未定义的属性“标题”
<% if (results.length == 0){ %>
<h1>No Matching Results</h1>
<% } else if(typeof results[i].id !== "undefined"){ %>
<a href="/second/<%= results[i].id %>">
<%= results[i].name %>
<% if(results[i].known_for[0].title) { %>
Known For: <%= results[i].known_for[0].title %>
<% } else { %>
Known For: Nothing
<% } %>
</a>
<% } %>
I just want it to output a title if it is provided and then have an else statement if it is not.我只是希望它在提供的情况下输出一个标题,如果没有,则有一个 else 语句。
<% if (results.length == 0){ %> <h1>No Matching Results</h1> <% } else if(typeof results[i].id !== "undefined"){ %> <a href="/second/<%= results[i].id %>"> <%= results[i].name %> <% if(results[i].known_for[0].title !== undefined || results[i].known_for[0].title !== "undefined" || results[i].known_for[0].title !== null) { %> Known For: <%= results[i].known_for[0].title %> <% } else { %> Known For: Nothing <% } %> </a> <% } %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.