简体   繁体   English

如何为对象的未定义属性捕获此错误?

[英]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.

相关问题 为什么我总是收到错误消息,指出对象属性未定义? - Why do I keep getting an error saying an object property is undefined? 如何不使用try / catch来解决“无法读取未定义的属性……”的问题? - How do I solve the “cannot read property … of undefined” with out using try/catch? 如何在 Javascript 中设置 object 属性的样式? 我收到“未捕获的类型错误:无法设置未定义的属性 'fontWeight'” - How do I style an object property in Javascript? I get “Uncaught TypeError: Cannot set property 'fontWeight' of undefined” 为什么我得到未定义错误的属性? - Why do I get property of undefined error? 如何捕获Firebase搜索错误? - how do I catch firebase search error? 如何在对象的属性上添加属性? - How do I add a property on a property of an object? 请问我该如何处理这个错误“未处理的拒绝(类型错误):无法读取未定义的属性'过滤器'” - Please how do i handle this error “Unhandled Rejection (Type Error): Cannot read property 'filter' of undefined” 为什么得到“无法读取该对象的未定义属性...”? - Why do I get "Cannot read property…of undefined with this object? 错误:未捕获TypeError:无法读取未定义的属性“ city”,并且如何在JavaScript中的对象键中包含破折号? - Error : Uncaught TypeError: Cannot read property 'city' of undefined and How can I include a dash in an object key in javascript? 读取对象属性时发生未定义的错误 - Undefined error in reading the property of object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM