Null-safe property access (and conditional assignment) in ES6/2015

后端 未结 10 1150
[愿得一人]
[愿得一人] 2020-11-22 13:00

Is there a null-safe property access (null propagation / existence) operator in ES6 (ES2015/JavaScript.next/Harmony) like ?. in

10条回答
  •  一整个雨季
    2020-11-22 13:55

    It's not as nice as the ?. operator, but to achieve a similar result you could do:

    user && user.address && user.address.postcode
    

    Since null and undefined are both falsy values (see this reference), the property after the && operator is only accessed if the precedent it not null or undefined.

    Alternatively, you could write a function like this:

    function _try(func, fallbackValue) {
        try {
            var value = func();
            return (value === null || value === undefined) ? fallbackValue : value;
        } catch (e) {
            return fallbackValue;
        }
    }
    

    Usage:

    _try(() => user.address.postcode) // return postcode or undefined 
    

    Or, with a fallback value:

    _try(() => user.address.postcode, "none") // return postcode or a custom string
    

提交回复
热议问题