在 JavaScript 中是否有类似于
string.Empty
的方法,或者只需要检查 ""
是否为空?string.Empty
的方法,或者只需要检查 ""
是否为空?忽略空格字符串,您可以使用此方法检查是否为null、空或未定义:
var obj = {};
(!!obj.str) // Returns false
obj.str = "";
(!!obj.str) // Returns false
obj.str = null;
(!!obj.str) // Returns false
这种方法简洁并且适用于未定义的属性,尽管它不是最易读的。
undefined
或null
要复杂一些。 - Flimm''
空字符串,可以像下面的代码一样简单:String.prototype.isEmpty = String.prototype.isEmpty || function() {
return !(!!this.length);
}
''
和带有空格的字符串' '
,您可以通过添加trim()
来实现,就像下面的代码一样:String.prototype.isEmpty = String.prototype.isEmpty || function() {
return !(!!this.trim().length);
}
你可以这样调用它:
''.isEmpty(); //return true
'alireza'.isEmpty(); //return false
!(!!this.length)
而不是只做 !this
(或者对于第二个选项,做 !this.trim()
)有什么好处?长度为零的字符串已经是虚假的了,括号是多余的,并且三次否定它与一次否定它完全相同。 - John Montgomery我通常会使用类似于以下的方法:
if (str == "") {
//Do Something
}
else {
//Do Something Else
}
==
运算符不是严格比较的。因此,如果 str == ""
,则 str
可能是 null
、undefined
、false
、0
、[]
等等。 - alexandre-rousseau试试这个
str.value.length == 0
str
等于undefined
或null
,则会抛出TypeError
。 - alexandre-rousseauconst isNonEmptyString = (value) => typeof(value) == 'string' && value.length > 0
试试这段代码:
function isEmpty(strValue)
{
// Test whether strValue is empty
if (!strValue || strValue.trim() === "" ||
(strValue.trim()).length === 0) {
// Do something
}
}
(strValue.trim()).length === 0)
的目的是什么?这不是和strValue.trim() === ""
重复了吗? - pys由于JavaScript是一种鸭子类型的语言,因此在过程中可能不知道数据何时以及如何更改,因此您应始终检查类型。因此,以下是更好的解决方案:
let undefinedStr;
if (!undefinedStr) {
console.log("String is undefined");
}
let emptyStr = "";
if (!emptyStr) {
console.log("String is empty");
}
let nullStr = null;
if (!nullStr) {
console.log("String is null");
}
undefined
。此答案未检查类型。 - Flimmvar j = undefined;
console.log((typeof j == 'undefined') ? "true":"false");
var j = null;
console.log((j == null) ? "true":"false");
var j = "";
console.log((!j) ? "true":"false");
var j = "Hi";
console.log((!j) ? "true":"false");
检查它是否为字符串类型且不为空:
const isNonEmptyString = (val) => typeof val === 'string' && !!val
null
或undefined
是空的呢?一个空字符串就是一个空字符串,它不是null
或undefined
。 - Flimm