Detecting an undefined object property

后端 未结 30 2945
花落未央
花落未央 2020-11-21 04:43

What\'s the best way of checking if an object property in JavaScript is undefined?

30条回答
  •  被撕碎了的回忆
    2020-11-21 05:34

    I provide three ways here for those who expect weird answers:

    function isUndefined1(val) {
        try {
            val.a;
        } catch (e) {
            return /undefined/.test(e.message);
        }
        return false;
    }
    
    function isUndefined2(val) {
        return !val && val+'' === 'undefined';
    }
    
    function isUndefined3(val) {
        const defaultVal = {};
        return ((input = defaultVal) => input === defaultVal)(val);
    }
    
    function test(func){
        console.group(`test start :`+func.name);
        console.log(func(undefined));
        console.log(func(null));
        console.log(func(1));
        console.log(func("1"));
        console.log(func(0));
        console.log(func({}));
        console.log(func(function () { }));
        console.groupEnd();
    }
    test(isUndefined1);
    test(isUndefined2);
    test(isUndefined3);

    isUndefined1:

    Try to get a property of the input value, and check the error message if it exists. If the input value is undefined, the error message would be Uncaught TypeError: Cannot read property 'b' of undefined.

    isUndefined2:

    Convert the input value to a string to compare with "undefined" and ensure it's a negative value.

    isUndefined3:

    In JavaScript, an optional parameter works when the input value is exactly undefined.

提交回复
热议问题