Two ways to avoid property access errors in JavaScript

    Querying a non-existent property will not report an error. If the property x is not found in the object o's own properties or inherited properties, the property access expression ox returns undefined.

    If the object does not exist, then trying to query the properties of the non-existing object will report an error (null and undefined values ​​have no properties and will report an error).

    Ways to avoid errors:

    (1) A redundant but well-understood approach:

var len = undefined;
if (book) {
    if (book.subtitle) len = book.subtitle.length;
}

    (2) A more concise common method (using the short-circuit behavior of the && operator):

var len = book && book.subtitle && book.subtitle.length;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325363625&siteId=291194637