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


当前回答

我通常用这样的东西,

if (!str.length) {
    // Do something
}

其他回答

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

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

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

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


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 === '')
  ...

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

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

用法:

checkEmpty(""); // returns true.
checkEmpty("mystr"); // returns 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

也可以使用正则表达式:

if((/^\s*$/).test(str)) { }

检查是否有空字符串或空白字符串。

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

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);
}