检查JavaScript变量是假的还是空数组或对象的最有效方法是什么?

时间:2017-12-25 12:54:29

标签: javascript arrays javascript-objects

我有一个用例,其中一个函数接收一个可以是各种类型的变量,包括一个数组或一个对象引用。

但是我想忽略传递的任何变量,这些变量在通常的JavaScript意义上是假的,而且我想处理空数组[]和空对象{}也是假的。

我可以立即看到有很多方法可以做到这一点,但我想知道假设一个非常现代的JavaScript实现和只有没有框架的vanilla JavaScript会有什么效率。

显而易见的方法是检查它是一个数组还是一个对象,并在数组的情况下检查.length,如果它是一个对象则检查Object.keys(x).length。但考虑到其他一些已经错误的东西也是typeof object,并且空阵列似乎表现得不真实或假,取决于你如何检查,我打赌有些方法更有效率也许更惯用。

3 个答案:

答案 0 :(得分:1)

以下内容应符合您的标准(虽然看起来很难看)。

if (
     sth &&                                                     // normal JS coercion
     (!Array.isArray(sth) || sth.length) &&                     // falsify empty arrays
     (Object.getPrototypeOf(sth) !== Object.prototype || Object.keys(sth).length)     // falsify empty objects
   ) 
alert("pass");

试验:

sth = [];                 // Don't Pass
sth = {};                 // Don't Pass
sth = null;               // Don't Pass
sth = false;              // Don't Pass
sth = undefined;          // Don't Pass
sth = "";                 // Don't Pass
sth = [1];                // Pass
sth = { a: "" }           // Pass
sth = new Date;           // Pass
sth = "a";                // Pass
sth = function(){}        // Pass

答案 1 :(得分:0)

检查sth是否真实:

 if(sth && (typeof sth !== "object" || Object.keys(sth).length))
   alert("passes");

答案 2 :(得分:0)

我一直在使用它。

function IsEmpty(val){
    return (!val || val == "" || (typeof(val) === "object" && Object.keys(val).length == 0) || val === [] || val === null || val === undefined);
} 

传递

的示例
if(IsEmpty(false)){console.log("pass");}
if(IsEmpty("")){console.log("pass");}
if(IsEmpty([])){console.log("pass");}
if(IsEmpty({})){console.log("pass");}
if(IsEmpty(null)){console.log("pass");}
if(IsEmpty()){console.log("pass");}

失败的例子

if(IsEmpty(true)){console.log("fail");}
if(IsEmpty("not null")){console.log("fail");}
if(IsEmpty([1])){console.log("fail");}
if(IsEmpty({"a":1})){console.log("fail");}

//!IsEmpty means is not empty
if(!IsEmpty(false)){console.log("fail");}
if(!IsEmpty("")){console.log("fail");}
if(!IsEmpty([])){console.log("fail");}
if(!IsEmpty({})){console.log("fail");}
if(!IsEmpty()){console.log("fail");}
相关问题