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


当前回答

您也应该经常检查类型,因为JavaScript是一种鸭子类型的语言,所以您可能不知道数据在过程中何时以及如何更改。因此,以下是更好的解决方案:

let undefinedStr;if(!undefinedStr){console.log(“字符串未定义”);}let emptyStr=“”;if(!emptyStr){console.log(“字符串为空”);}让nullStr=null;if(!nullStr){console.log(“字符串为空”);}

其他回答

这里有很多有用的信息,但在我看来,其中一个最重要的因素没有得到解决。

null、undefined和“”都是假的。

当计算空字符串时,通常是因为需要用其他东西替换它。

在这种情况下,您可以预期以下行为。

var a = ""
var b = null
var c = undefined

console.log(a || "falsy string provided") // prints ->"falsy string provided"
console.log(b || "falsy string provided") // prints ->"falsy string provided"
console.log(c || "falsy string provided") // prints ->"falsy string provided"

考虑到这一点,可以返回字符串是否为“”、null或undefined(无效字符串)与有效字符串的方法或函数如下所示:

const validStr = (str) => str ? true : false

validStr(undefined) // returns false
validStr(null) // returns false
validStr("") // returns false
validStr("My String") // returns true

Undercore.js JavaScript库,http://underscorejs.org/,提供了一个非常有用的_.isEmpty()函数,用于检查空字符串和其他空对象。

参考:http://underscorejs.org/#isEmpty

isEmpty _.isEmpty(对象)如果可枚举对象不包含值(无可枚举的所有者属性),则返回true。对于字符串和类似数组的对象_.isEmpty检查长度属性是否为0。_.is空([1,2,3]);=>假_.isEmpty({});=>真

其他非常有用的Undercore.js函数包括:

http://underscorejs.org/#isNull_.isNull(对象)http://underscorejs.org/#isUndefined_.is未定义(值)http://underscorejs.org/#has_.有(对象,键)

我使用组合,最快的检查是第一个。

function isBlank(pString) {
    if (!pString) {
        return true;
    }
    // Checks for a non-white space character
    // which I think [citation needed] is faster
    // than removing all the whitespace and checking
    // against an empty string
    return !/[^\s]+/.test(pString);
}

我使用:

function empty(e) {
  switch (e) {
    case "":
    case 0:
    case "0":
    case null:
    case false:
    case undefined:
      return true;
    default:
      return false;
  }
}

empty(null) // true
empty(0) // true
empty(7) // false
empty("") // true
empty((function() {
    return ""
})) // false

开始于:

return (!value || value == undefined || value == "" || value.length == 0);

查看最后一个条件,如果值==“”,则其长度必须为0。因此,删除它:

return (!value || value == undefined || value == "");

但是等等!在JavaScript中,空字符串为false。因此,下降值==“”:

return (!value || value == undefined);

和undefined为true,因此不需要检查。因此,我们有:

return (!value);

我们不需要括号:

return !value