如何在JavaScript中检查空/未定义/空字符串?

我看到了这个线程 ,可是没有看到JavaScript特定的示例。 是否有一个简单的string.Empty在JavaScript中可用,仍是仅检查""一种状况? html


#1楼

忽略空格字符串,您可使用它来检查null,empty和undefined: web

var obj = {};
(!!obj.str) //returns false

obj.str = "";
(!!obj.str) //returns false

obj.str = null;
(!!obj.str) //returns false

简洁,它适用于未定义的属性,尽管它不是最易读的。 测试


#2楼

我没有注意到一个考虑到字符串中可能存在空字符的答案。 例如,若是咱们有一个空字符串: this

var y = "\0"; // an empty string, but has a null character
(y === "") // false, testing against an empty string does not work
(y.length === 0) // false
(y) // true, this is also not expected
(y.match(/^[\s]*$/)) // false, again not wanted

要测试其无效性,能够执行如下操做: spa

String.prototype.isNull = function(){ 
  return Boolean(this.match(/^[\0]*$/)); 
}
...
"\0".isNull() // true

它适用于空字符串和空字符串,而且全部字符串都可访问。 另外,它能够扩展为包含其余JavaScript空字符或空格字符(即,不间断空格,字节顺序标记,行/段落分隔符等)。 prototype


#3楼

尝试: 线程

if (str && str.trim().length) {  
    //...
}

#4楼

若是您只想检查是否有任何价值,能够 code

if (strValue) {
    //do something
}

若是您须要专门检查是否有一个空字符串,而不是null,那么我认为使用===运算符来检查""是最好的选择(这样您就能够知道它其实是您要与之进行比较的字符串) )。 htm

if (strValue === "") {
    //...
}

#5楼

我不会太担忧最有效的方法。 使用最清楚您意图的内容。 对我来讲,一般是strVar == ""ip

编辑:来自康斯坦丁的评论,若是strVar可能最终包含一个整数0值,那么那确实是那些意图明确的状况之一。

相关文章
相关标签/搜索