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


当前回答

前面的所有答案都很好,但这会更好。使用双NOT运算符(!!):

if (!!str) {
    // Some code here
}

或使用类型铸造:

if (Boolean(str)) {
    // Code here
}

两者的功能相同。将变量类型转换为Boolean,其中str是一个变量。

对于null、undefined、0000、“”、false,它返回false。对于除空字符串之外的所有字符串值(包括“0”和“”等字符串),它都返回true

其他回答

空字符串,未定义,null。。。

检查真实值:

if (strValue) {
    // strValue was non-empty string, true, 42, Infinity, [], ...
}

要检查错误值,请执行以下操作:

if (!strValue) {
    // strValue was empty string, false, 0, null, undefined, ...
}

空字符串(仅限!)

要检查是否正好为空字符串,请使用==运算符与“”进行严格相等比较:

if (strValue === "") {
    // strValue was empty string
}

要严格检查非空字符串,请使用!==操作员:

if (strValue !== "") {
    // strValue was not an empty string
}

我使用:

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

我宁愿使用非空白测试而不是空白测试

function isNotBlank(str) {
   return (str && /^\s*$/.test(str));
}

我不会太担心最有效的方法。使用最明确的意图。对我来说,这通常是strVar==“”。

根据Constantin的评论,如果strVar可以包含一个0整数值,那么这确实是一种意图明确的情况。

var s; // undefined
var s = ""; // ""
s.length // 0

JavaScript中没有表示空字符串的内容。检查长度(如果您知道var始终是字符串)或“”