等同于JavaScript isset()

JavaScript

Green猿古一

2020-03-12

在PHP中可以做到if(isset($array['foo'])) { ... }在JavaScript中,您通常会使用if(array.foo) { ... }相同的方法,但这并不完全相同。如果array.foo确实存在,但条件是false0(或可能还有其他值),则条件也将评估为false

issetJavaScript 中PHP的完美替代品是什么?

从更广泛的意义上讲,有关JavaScript处理不存在的变量,没有值的变量等的通用完整指南会很方便。

第1065篇《等同于JavaScript isset()》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

3个回答
番长GO 2020.03.12

I use a function that can check variables and objects. very convenient to work with jQuery

    function _isset (variable) {
        if(typeof(variable) == "undefined" || variable == null)
            return false;
        else
            if(typeof(variable) == "object" && !variable.length) 
                return false;
            else
                return true;
    };
猴子飞云 2020.03.12

这个简单的解决方案有效,但不适用于深层对象检查。

function isset(str) {
    return window[str] !== undefined;
}
阿飞猿 2020.03.12

If you are using underscorejs I always use

if (!_.isUndefined(data) && !_.isNull(data)) {
     //your stuff
}

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android