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


当前回答

以下正则表达式是另一种解决方案,可用于null、空或未定义的字符串。

(/(null|undefined|^$)/).test(null)

我添加了这个解决方案,因为它可以进一步扩展,以检查空值或某些值,如下所示。下面的正则表达式正在检查字符串是否可以是空的、空的、未定义的或只有整数。

(/(null|undefined|^$|^\d+$)/).test()

其他回答

下面是我用来处理这个问题的一些自定义函数。以及代码如何运行的示例。

常量v1=0常量v2=“4”常量v2e=未定义常量v2e2=空常量v3=[1,2,3,4]常量v3e=[]常量v4=真常量v4e=假常量v5={测试:'值'}常量v5e={}常量v6=“NotEmpty”常量v6e=“”函数为Numeric(n){回来isNaN(parseFloat(n))&&isFinite(n)}函数isEmpty(v,zeroIsEmpty=false){/***当执行类型检查时,null将始终返回“object”,因此我们首先过滤掉它*@参见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof#typeof_null*/如果(v==空){返回true}如果(v==真){return false}if(类型v==='对象'){回来对象键(v)长度}如果(isNumeric(v)){返回zeroIsEmpty?parseFloat(v)==0:false}回来v | |!v.length | | v.length<1}console.log(isEmpty(v1),isEmpty(v1,true))console.log(isEmpty(v2),isEmptyconsole.log(isEmpty(v3),isEmpty(v3e))console.log(isEmpty(v4),isEmptyconsole.log(isEmpty(v5),isEmptyconsole.log(isEmpty(v6),isEmpty(v6e))

同样作为参考,以下是Lodash isEmpty的来源:

检查您是否试图传递未定义的术语也是一个好主意。

function TestMe() {
  if((typeof str != 'undefined') && str) {
    alert(str);
  }
 };

TestMe();

var str = 'hello';

TestMe();

我通常遇到这样的情况:当对象实例的字符串属性不为空时,我想做一些事情。这很好,只是属性并不总是存在。

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' />

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

Undercore.js JavaScript库,http://underscorejs.org/,提供了一个非常有用的_.isEmpty()函数,用于检查空字符串和其他空对象。

参考:http://underscorejs.org/#isEmpty

isEmpty _.isEmpty(对象)如果可枚举对象不包含值(无可枚举的所有者属性),则返回true。对于字符串和类似数组的对象_.isEmpty检查长度属性是否为0。_.is空([1,2,3]);=>假_.isEmpty({});=>真

其他非常有用的Undercore.js函数包括:

http://underscorejs.org/#isNull_.isNull(对象)http://underscorejs.org/#isUndefined_.is未定义(值)http://underscorejs.org/#has_.有(对象,键)

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