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


当前回答

非常通用的“All-In-One”功能(但不推荐):

function is_empty(x)
{
    return (                                                           //don't put newline after return
        (typeof x == 'undefined')
              ||
        (x == null)
              ||
        (x == false)        //same as: !x
              ||
        (x.length == 0)
              ||
        (x == 0)            // note this line, you might not need this. 
              ||
        (x == "")
              ||
        (x.replace(/\s/g,"") == "")
              ||
        (!/[^\s]/.test(x))
              ||
        (/^\s*$/.test(x))
    );
}

但是,我不建议使用它,因为您的目标变量应该是特定类型的(即字符串、数字或对象?),所以应用与该变量相关的检查。

其他回答

空字符串,未定义,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
}

我在这里没有找到好答案(至少没有适合我的答案)

所以我决定自己回答:

value==未定义| | value==null | | value===“”;

你需要开始检查它是否未定义。否则,您的方法可能会爆炸,然后您可以检查它是否等于null或等于空字符串。

你不能拥有!!或者仅当(value),因为如果你勾选0,它会给你一个错误的答案(0是错误的)。

话虽如此,用如下方法将其包装起来:

公共静态isEmpty(值:any):布尔值{返回值==未定义| |值==null | |值===“”;}

PS.:你不需要检查typeof,因为它甚至在进入方法之前就会爆炸并抛出

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

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

不要假设您检查的变量是字符串。不要假设这个变量有一个长度,那么它就是一个字符串。

问题是:仔细思考你的应用程序必须做什么,可以接受什么。打造强健的体魄。

如果您的方法/函数只处理非空字符串,那么测试参数是否为非空字符串并且不要做一些“技巧”。

作为一个例子,如果你不小心遵循这里的一些建议,就会发生爆炸。


var getLastChar = function (str) {
 if (str.length > 0)
   return str.charAt(str.length - 1)
}

getLastChar('hello')
=> "o"

getLastChar([0,1,2,3])
=> TypeError: Object [object Array] has no method 'charAt'

所以,我会坚持


if (myVar === '')
  ...

试试这个

str.value.length == 0