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


当前回答

function tell()
{
    var pass = document.getElementById('pasword').value;
    var plen = pass.length;

    // Now you can check if your string is empty as like
    if(plen==0)
    {
        alert('empty');
    }
    else
    {
        alert('you entered something');
    }
}

<input type='text' id='pasword' />

这也是检查字段是否为空的通用方法。

其他回答

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

您可以验证以下方法并了解其区别。

var j=未定义;console.log((typeof j==“undefined”)?“真”:“假”);var j=空;console.log((j==null)?“真”:“假”);var j=“”;console.log((!j)?“真”:“假”);var j=“Hi”;console.log((!j)?“真”:“假”);

有很多答案,还有很多不同的可能性!

毫无疑问,快速简单的实现是赢家:if(!str.length){…}

然而,还有许多其他例子。我建议,最好的功能方法是:

函数为空(str){if(str类型==‘undefined‘||!str | | str.length==0 | | str==“”||!/[^\s]/.test(str)||/^\s*$/.test(str)|| str.replace(/\s/g,“”)==“)返回true;其他的return false;}

我知道有点过分了。

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

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

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

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