JavaScript中是否存在字符串.Empty,还是只是检查“”?


当前回答

尝试以下代码:

function isEmpty(strValue)
{
    // Test whether strValue is empty
    if (!strValue || strValue.trim() === "" ||
        (strValue.trim()).length === 0) {
        // Do something
    }
}

其他回答

isBlank函数的最终和最短变体:

/***将返回:*False for:对于所有带字符的字符串*True for:false,null,undefined,0,0.0,“”,“”。**@param字符串*@return{boolean}*/函数isBlank(str){return(!!!str||/^\s*$/.test(str));}//测试console.log(“isBlank TRUE变量:”);console.log(isBlank(false));console.log(isBlank(未定义));console.log(isBlank(null));console.log(isBlank(0));console.log(isBlank(0.0));console.log(isBlank(“”));console.log(isBlank(“”));console.log(“isBlank FALSE变量:”);console.log(isBlank(“0”));console.log(isBlank(“0.0”));console.log(isBlank(“0”));console.log(isBlank(“0”));console.log(isBlank(“测试字符串”));console.log(isBlank(“true”));console.log(isBlank(“false”));console.log(isBlank(“null”));console.log(isBlank(“未定义”));

您可以使用lodash:_.isEmpty(值)。

它涵盖了许多情况,如{}、“”、null、undefined等。

但对于JavaScript原始数据类型的Number类型(如_.isEmpty(10)或_.isEmpty(Number.MAX_VALUE)),它总是返回true。

尝试以下代码:

function isEmpty(strValue)
{
    // Test whether strValue is empty
    if (!strValue || strValue.trim() === "" ||
        (strValue.trim()).length === 0) {
        // Do something
    }
}

没有isEmpty()方法,您必须检查类型和长度:

if (typeof test === 'string' && test.length === 0){
  ...

当测试未定义或为空时,需要进行类型检查以避免运行时错误。

嗯,检查这个的最简单的函数是。。。

const checkEmpty=string=>(strim.trim()==“”)||!strim.trim();

用法:

checkEmpty(""); // returns true.
checkEmpty("mystr"); // returns false.

就是这么简单。:)