简体   繁体   中英

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. 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:

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.

 <% 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> <% } %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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