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

发布于 2024-07-06 06:20:15 字数 76 浏览 8 评论 0 原文

JavaScript 中是否有 string.Empty,或者只是检查 "" 的情况?

Is there a string.Empty in JavaScript, or is it just a case of checking for ""?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

墨落成白 2024-07-13 06:20:15

我用:

function empty(e) {
  switch (e) {
    case "":
    case 0:
    case "0":
    case null:
    case false:
    case undefined:
      return true;
    default:
      return false;
  }
}

empty(null) // true
empty(0) // true
empty(7) // false
empty("") // true
empty((function() {
    return ""
})) // false

I use:

function empty(e) {
  switch (e) {
    case "":
    case 0:
    case "0":
    case null:
    case false:
    case undefined:
      return true;
    default:
      return false;
  }
}

empty(null) // true
empty(0) // true
empty(7) // false
empty("") // true
empty((function() {
    return ""
})) // false
街角卖回忆 2024-07-13 06:20:15

性能

我在 macOS v10.13.6 (High Sierra) 上对 18 个选定的解决方案进行了测试。 解决方案的工作方式略有不同(对于极端情况输入数据),如下面的代码片段所示。

结论

  • 基于!str=====length 对于所有浏览器(A、B、C、G、I、J)都很快
  • 基于正则表达式(testreplace)和 的解决方案charAt 对于所有浏览器(H、L、M、P)来说都是最慢的,
  • 标记为最快的解决方案仅在一次测试运行中是最快的 - 但在许多运行中,它在“快速”解决方案组内发生了变化

在此处输入图像描述

详细信息

在下面的代码片段中,我通过使用不同的输入参数来比较所选 18 种方法的结果

  • "" "a" " "- 空字符串,带字母的字符串和带空格的字符串
  • [] {} f - 数组、对象和函数
  • 0 1 NaN Infinity - 数字
  • true false - 布尔
  • null <代码>未定义

并非所有测试方法都支持所有输入情况。

function A(str) {
  let r=1;
  if (!str)
    r=0;
  return r;
}

function B(str) {
  let r=1;
  if (str == "")
    r=0;
  return r;
}

function C(str) {
  let r=1;
  if (str === "")
    r=0;
  return r;
}

function D(str) {
  let r=1;
  if(!str || 0 === str.length)
    r=0;
  return r;
}

function E(str) {
  let r=1;
  if(!str || /^\s*$/.test(str))
    r=0;
  return r;
}

function F(str) {
  let r=1;
  if(!Boolean(str))
    r=0;
  return r;
}

function G(str) {
  let r=1;
  if(! ((typeof str != 'undefined') && str) )
    r=0;
  return r;
}

function H(str) {
  let r=1;
  if(!/\S/.test(str))
    r=0;
  return r;
}

function I(str) {
  let r=1;
  if (!str.length)
    r=0;
  return r;
}

function J(str) {
  let r=1;
  if(str.length <= 0)
    r=0;
  return r;
}

function K(str) {
  let r=1;
  if(str.length === 0 || !str.trim())
    r=0;
  return r;
}

function L(str) {
  let r=1;
  if ( str.replace(/\s/g,"") == "")
    r=0;
  return r;
}

function M(str) {
  let r=1;
  if((/^\s*$/).test(str))
    r=0;
  return r;
}


function N(str) {
  let r=1;
  if(!str || !str.trim().length)
    r=0;
  return r;
}

function O(str) {
  let r=1;
  if(!str || !str.trim())
    r=0;
  return r;
}

function P(str) {
  let r=1;
  if(!str.charAt(0))
    r=0;
  return r;
}

function Q(str) {
  let r=1;
  if(!str || (str.trim()==''))
    r=0;
  return r;
}

function R(str) {
  let r=1;
  if (typeof str == 'undefined' ||
      !str ||
      str.length === 0 ||
      str === "" ||
      !/[^\s]/.test(str) ||
      /^\s*$/.test(str) ||
      str.replace(/\s/g,"") === "")

    r=0;
  return r;
}




// --- TEST ---

console.log(                  '   ""  "a"  " " [] {} 0 1 NaN Infinity f true false null undefined ');
let log1 = (s,f)=> console.log(`${s}: ${f("")}   ${f("a")}    ${f(" ")}   ${f([])}  ${f({})}  ${f(0)} ${f(1)} ${f(NaN)}   ${f(Infinity)}        ${f(f)} ${f(true)}    ${f(false)}     ${f(null)}    ${f(undefined)}`);
let log2 = (s,f)=> console.log(`${s}: ${f("")}   ${f("a")}    ${f(" ")}   ${f([])}  ${f({})}  ${f(0)} ${f(1)} ${f(NaN)}   ${f(Infinity)}        ${f(f)} ${f(true)}    ${f(false)}`);
let log3 = (s,f)=> console.log(`${s}: ${f("")}   ${f("a")}    ${f(" ")}`);

log1('A', A);
log1('B', B);
log1('C', C);
log1('D', D);
log1('E', E);
log1('F', F);
log1('G', G);
log1('H', H);

log2('I', I);
log2('J', J);

log3('K', K);
log3('L', L);
log3('M', M);
log3('N', N);
log3('O', O);
log3('P', P);
log3('Q', Q);
log3('R', R);

然后,对于所有方法,我都会针对 Chrome v78.0.0、Safari v13.0.4 和 Firefox v71.0.0 浏览器执行速度测试用例 str = "" - 您可以在您的计算机上运行测试 此处

在此处输入图像描述

Performance

I perform tests on macOS v10.13.6 (High Sierra) for 18 chosen solutions. Solutions works slightly different (for corner-case input data) which was presented in the snippet below.

Conclusions

  • the simple solutions based on !str,==,=== and length are fast for all browsers (A,B,C,G,I,J)
  • the solutions based on the regular expression (test,replace) and charAt are slowest for all browsers (H,L,M,P)
  • the solutions marked as fastest was fastest only for one test run - but in many runs it changes inside 'fast' solutions group

Enter image description here

Details

In the below snippet I compare results of chosen 18 methods by use different input parameters

  • "" "a" " "- empty string, string with letter and string with space
  • [] {} f- array, object and function
  • 0 1 NaN Infinity - numbers
  • true false - Boolean
  • null undefined

Not all tested methods support all input cases.

function A(str) {
  let r=1;
  if (!str)
    r=0;
  return r;
}

function B(str) {
  let r=1;
  if (str == "")
    r=0;
  return r;
}

function C(str) {
  let r=1;
  if (str === "")
    r=0;
  return r;
}

function D(str) {
  let r=1;
  if(!str || 0 === str.length)
    r=0;
  return r;
}

function E(str) {
  let r=1;
  if(!str || /^\s*$/.test(str))
    r=0;
  return r;
}

function F(str) {
  let r=1;
  if(!Boolean(str))
    r=0;
  return r;
}

function G(str) {
  let r=1;
  if(! ((typeof str != 'undefined') && str) )
    r=0;
  return r;
}

function H(str) {
  let r=1;
  if(!/\S/.test(str))
    r=0;
  return r;
}

function I(str) {
  let r=1;
  if (!str.length)
    r=0;
  return r;
}

function J(str) {
  let r=1;
  if(str.length <= 0)
    r=0;
  return r;
}

function K(str) {
  let r=1;
  if(str.length === 0 || !str.trim())
    r=0;
  return r;
}

function L(str) {
  let r=1;
  if ( str.replace(/\s/g,"") == "")
    r=0;
  return r;
}

function M(str) {
  let r=1;
  if((/^\s*$/).test(str))
    r=0;
  return r;
}


function N(str) {
  let r=1;
  if(!str || !str.trim().length)
    r=0;
  return r;
}

function O(str) {
  let r=1;
  if(!str || !str.trim())
    r=0;
  return r;
}

function P(str) {
  let r=1;
  if(!str.charAt(0))
    r=0;
  return r;
}

function Q(str) {
  let r=1;
  if(!str || (str.trim()==''))
    r=0;
  return r;
}

function R(str) {
  let r=1;
  if (typeof str == 'undefined' ||
      !str ||
      str.length === 0 ||
      str === "" ||
      !/[^\s]/.test(str) ||
      /^\s*$/.test(str) ||
      str.replace(/\s/g,"") === "")

    r=0;
  return r;
}




// --- TEST ---

console.log(                  '   ""  "a"  " " [] {} 0 1 NaN Infinity f true false null undefined ');
let log1 = (s,f)=> console.log(`${s}: ${f("")}   ${f("a")}    ${f(" ")}   ${f([])}  ${f({})}  ${f(0)} ${f(1)} ${f(NaN)}   ${f(Infinity)}        ${f(f)} ${f(true)}    ${f(false)}     ${f(null)}    ${f(undefined)}`);
let log2 = (s,f)=> console.log(`${s}: ${f("")}   ${f("a")}    ${f(" ")}   ${f([])}  ${f({})}  ${f(0)} ${f(1)} ${f(NaN)}   ${f(Infinity)}        ${f(f)} ${f(true)}    ${f(false)}`);
let log3 = (s,f)=> console.log(`${s}: ${f("")}   ${f("a")}    ${f(" ")}`);

log1('A', A);
log1('B', B);
log1('C', C);
log1('D', D);
log1('E', E);
log1('F', F);
log1('G', G);
log1('H', H);

log2('I', I);
log2('J', J);

log3('K', K);
log3('L', L);
log3('M', M);
log3('N', N);
log3('O', O);
log3('P', P);
log3('Q', Q);
log3('R', R);

And then for all methods I perform speed test case str = "" for browsers Chrome v78.0.0, Safari v13.0.4, and Firefox v71.0.0 - you can run tests on your machine here

Enter image description here

差↓一点笑了 2024-07-13 06:20:15

前面的所有答案都很好,但这个会更好。 使用双 NOT 运算符 (!!):

if (!!str) {
    // Some code here
}

或使用类型转换:

if (Boolean(str)) {
    // Code here
}

两者执行相同的功能。 将变量类型转换为布尔值,其中 str 是一个变量。

  • 对于 nullundefined0000“”

  • 对于除空字符串之外的所有字符串值(包括 "0"" " 等字符串),它返回 true

    >

All the previous answers are good, but this will be even better. Use dual NOT operators (!!):

if (!!str) {
    // Some code here
}

Or use type casting:

if (Boolean(str)) {
    // Code here
}

Both do the same function. Typecast the variable to Boolean, where str is a variable.

  • It returns false for null, undefined, 0, 000, "", false.

  • It returns true for all string values other than the empty string (including strings like "0" and " ")

飞烟轻若梦 2024-07-13 06:20:15

您可以得到的最接近 str.Empty (前提是 str 是一个字符串)是:

if (!str.length) { ...

The closest thing you can get to str.Empty (with the precondition that str is a String) is:

if (!str.length) { ...
霞映澄塘 2024-07-13 06:20:15

如果您需要确保字符串不仅仅是一堆空格(我假设这是用于表单验证),您需要对空格进行替换。

if(str.replace(/\s/g,"") == ""){
}

If you need to make sure that the string is not just a bunch of empty spaces (I'm assuming this is for form validation) you need to do a replace on the spaces.

if(str.replace(/\s/g,"") == ""){
}
谜兔 2024-07-13 06:20:15

空字符串、未定义、null、...

检查真实值

if (strValue) {
    // strValue was non-empty string, true, 42, Infinity, [], ...
}

检查 falsy 值

if (!strValue) {
    // strValue was empty string, false, 0, null, undefined, ...
}

空字符串(仅限!)

要检查是否为空字符串,请使用 进行严格相等比较/Operators/Strict_equality" rel="noreferrer">=== 运算符

if (strValue === "") {
    // strValue was empty string
}

要严格检查是否为空字符串,请使用 !== 运算符

if (strValue !== "") {
    // strValue was not an empty string
}

Empty string, undefined, null, ...

To check for a truthy value:

if (strValue) {
    // strValue was non-empty string, true, 42, Infinity, [], ...
}

To check for a falsy value:

if (!strValue) {
    // strValue was empty string, false, 0, null, undefined, ...
}

Empty string (only!)

To check for exactly an empty string, compare for strict equality against "" using the === operator:

if (strValue === "") {
    // strValue was empty string
}

To check for not an empty string strictly, use the !== operator:

if (strValue !== "") {
    // strValue was not an empty string
}
扎心 2024-07-13 06:20:15

用于检查变量是否 falsey 或者它的长度属性是否等于零(对于字符串来说,意味着它是空的),我使用:

function isEmpty(str) {
    return (!str || str.length === 0 );
}

(请注意,字符串不是唯一具有 length 属性的变量,例如,数组也有它们。 )

或者,您可以使用(不是这样)新的可选链接和箭头函数来简化:

const isEmpty = (str) => (!str?.length);

它将检查长度,如果值为 null,则返回 undefined,而不会引发错误。 在空值的情况下,零是假的,结果仍然有效。

为了检查变量是否为 false 或者字符串是否仅包含空格或为空,我使用:

function isBlank(str) {
    return (!str || /^\s*$/.test(str));
}

如果需要,您可以 monkey-patch String 原型如下:

String.prototype.isEmpty = function() {
    // This doesn't work the same way as the isEmpty function used 
    // in the first example, it will return true for strings containing only whitespace
    return (this.length === 0 || !this.trim());
};
console.log("example".isEmpty());

请注意,monkey-patching 内置类型是有争议的,因为它无论出于何种原因,都可以破坏依赖于内置类型的现有结构的代码。

For checking if a variable is falsey or if it has length attribute equal to zero (which for a string, means it is empty), I use:

function isEmpty(str) {
    return (!str || str.length === 0 );
}

(Note that strings aren't the only variables with a length attribute, arrays have them as well, for example.)

Alternativaly, you can use the (not so) newly optional chaining and arrow functions to simplify:

const isEmpty = (str) => (!str?.length);

It will check the length, returning undefined in case of a nullish value, without throwing an error. In the case of an empty value, zero is falsy and the result is still valid.

For checking if a variable is falsey or if the string only contains whitespace or is empty, I use:

function isBlank(str) {
    return (!str || /^\s*$/.test(str));
}

If you want, you can monkey-patch the String prototype like this:

String.prototype.isEmpty = function() {
    // This doesn't work the same way as the isEmpty function used 
    // in the first example, it will return true for strings containing only whitespace
    return (this.length === 0 || !this.trim());
};
console.log("example".isEmpty());

Note that monkey-patching built-in types are controversial, as it can break code that depends on the existing structure of built-in types, for whatever reason.

筱武穆 2024-07-13 06:20:15

非常通用的“一体化”函数(但不推荐):

function is_empty(x)
{
    return (                                                           //don't put newline after return
        (typeof x == 'undefined')
              ||
        (x == null)
              ||
        (x == false)        //same as: !x
              ||
        (x.length == 0)
              ||
        (x == 0)            // note this line, you might not need this. 
              ||
        (x == "")
              ||
        (x.replace(/\s/g,"") == "")
              ||
        (!/[^\s]/.test(x))
              ||
        (/^\s*$/.test(x))
    );
}

但是,我不建议使用它,因为您的目标变量应该是特定类型(即字符串或数字,或对象?),因此应用与该变量相关的检查。

Very generic "All-In-One" Function (not recommended though):

function is_empty(x)
{
    return (                                                           //don't put newline after return
        (typeof x == 'undefined')
              ||
        (x == null)
              ||
        (x == false)        //same as: !x
              ||
        (x.length == 0)
              ||
        (x == 0)            // note this line, you might not need this. 
              ||
        (x == "")
              ||
        (x.replace(/\s/g,"") == "")
              ||
        (!/[^\s]/.test(x))
              ||
        (/^\s*$/.test(x))
    );
}

However, I don't recommend to use that, because your target variable should be of specific type (i.e. string, or numeric, or object?), so apply the checks that are relative to that variable.

亚希 2024-07-13 06:20:15

您可以使用 lodash
_.isEmpty(值)。

它涵盖了很多情况,例如 {}''nullundefined 等。

但它总是对于 JavaScript 原始数据类型,如 _.isEmpty(10)_.isEmpty(Number.MAX_VALUE) 均返回 true

You can use lodash:
_.isEmpty(value).

It covers a lot of cases like {}, '', null, undefined, etc.

But it always returns true for Number type of JavaScript primitive data types like _.isEmpty(10) or _.isEmpty(Number.MAX_VALUE) both returns true.

魂牵梦绕锁你心扉 2024-07-13 06:20:15

尝试:

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

Try:

if (str && str.trim().length) {  
    //...
}
原谅过去的我 2024-07-13 06:20:15

我不会太担心最有效的方法。 使用最符合您意图的内容。 对我来说,通常是 strVar == ""

根据 Constantin 的评论,如果 strVar 可能最终包含一个整数 0 值,那么这确实是 1那些澄清意图的情况。

I would not worry too much about the most efficient method. Use what is most clear to your intention. For me that's usually strVar == "".

As per the comment from Constantin, if strVar could some how end up containing an integer 0 value, then that would indeed be one of those intention-clarifying situations.

七堇年 2024-07-13 06:20:15
if ((input?.trim()?.length || 0) > 0) {
   // input must not be any of:
   // undefined
   // null
   // ""
   // " " or just whitespace
}

或者以函数形式:

const isNotNilOrWhitespace = input => (input?.trim()?.length || 0) > 0;

const isNilOrWhitespace = input => (input?.trim()?.length || 0) === 0;

说明:

如果 inputundefinednull 则 null 合并 ?. 将导致input?.trim()?.length 将为 undefinednull。 与 0 进行或运算 (||) 将得到 00 不是 > 0 因此结果将为 false,即它是一个 nil 值。

如果 input 为空或空格,则 .trim() 将删除前导和结尾空格,这将使空输入保持不变,并将任何空格转换为空值。 那么空字符串的长度就是0,并且如上,0并不是>0。 0,因此结果将为false,即它是空的或只有空格。

如果input是任何其他字符串,它的长度将> 0 在调用 .trim() 后,因此结果将为 true,即它不是 nil 值,也不是空值或只有空格。

if ((input?.trim()?.length || 0) > 0) {
   // input must not be any of:
   // undefined
   // null
   // ""
   // " " or just whitespace
}

Or in function form:

const isNotNilOrWhitespace = input => (input?.trim()?.length || 0) > 0;

const isNilOrWhitespace = input => (input?.trim()?.length || 0) === 0;

Explanation:

If input is undefined or null then the null coalescing ?. will result in input?.trim()?.length will be undefined or null. ORing (||) that with 0 will give 0. 0 is not > 0 therefore the result will be false, ie it IS a nil value.

If input is empty or whitespace then .trim() will remove leading and ending whitespace, which will keep an empty input the same, and convert any whitespace to an empty value. The length of an empty string is then 0, and as above, 0 is not > 0, therefore the result will be false, ie it IS empty or only whitespace.

If input is any other string, it's length will be > 0 after calling .trim(), and therefore the result will be true, ie it IS NOT a nil value, and it IS NOT empty or only whitespace.

唠甜嗑 2024-07-13 06:20:15
var s; // undefined
var s = ""; // ""
s.length // 0

JavaScript 中没有任何东西代表空字符串。 检查 length (如果您知道 var 始终是字符串)或 ""

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

There's nothing representing an empty string in JavaScript. Do a check against either length (if you know that the var will always be a string) or against ""

宫墨修音 2024-07-13 06:20:15

这里有很多有用的信息,但在我看来,最重要的元素之一没有得到解决。

nullundefined"" 都是 falsy

当评估空字符串时,通常是因为您需要用其他东西替换它。

在这种情况下,您可能会出现以下行为。

var a = ""
var b = null
var c = undefined

console.log(a || "falsy string provided") // prints ->"falsy string provided"
console.log(b || "falsy string provided") // prints ->"falsy string provided"
console.log(c || "falsy string provided") // prints ->"falsy string provided"

考虑到这一点,可以返回字符串是否为 ""nullundefined(无效字符串)的方法或函数) 与有效字符串的比较就这么简单:

const validStr = (str) => str ? true : false

validStr(undefined) // returns false
validStr(null) // returns false
validStr("") // returns false
validStr("My String") // returns true

请注意,您可能还想 trim() 字符串,因为 "" !== " "

There is a lot of useful information here, but in my opinion, one of the most important elements was not addressed.

null, undefined, and "" are all falsy.

When evaluating an empty string, it's often because you need to replace it with something else.

In this case, you can expect the following behavior.

var a = ""
var b = null
var c = undefined

console.log(a || "falsy string provided") // prints ->"falsy string provided"
console.log(b || "falsy string provided") // prints ->"falsy string provided"
console.log(c || "falsy string provided") // prints ->"falsy string provided"

With that in mind, a method or function that can return whether or not a string is "", null, or undefined (an invalid string) versus a valid string is as simple as this:

const validStr = (str) => str ? true : false

validStr(undefined) // returns false
validStr(null) // returns false
validStr("") // returns false
validStr("My String") // returns true

Please note, you probably also want to trim() the string since "" !== " ".

一场信仰旅途 2024-07-13 06:20:15

同时,我们可以有一个函数来检查所有“空”,例如 null、undefined、''、' '、{}、[]
所以我就写了这个。

var isEmpty = function(data) {
    if(typeof(data) === 'object'){
        if(JSON.stringify(data) === '{}' || JSON.stringify(data) === '[]'){
            return true;
        }else if(!data){
            return true;
        }
        return false;
    }else if(typeof(data) === 'string'){
        if(!data.trim()){
            return true;
        }
        return false;
    }else if(typeof(data) === 'undefined'){
        return true;
    }else{
        return false;
    }
}

使用案例和结果。

console.log(isEmpty()); // true
console.log(isEmpty(null)); // true
console.log(isEmpty('')); // true
console.log(isEmpty('  ')); // true
console.log(isEmpty(undefined)); // true
console.log(isEmpty({})); // true
console.log(isEmpty([])); // true
console.log(isEmpty(0)); // false
console.log(isEmpty('Hey')); // false

Meanwhile we can have one function that checks for all 'empties' like null, undefined, '', ' ', {}, [].
So I just wrote this.

var isEmpty = function(data) {
    if(typeof(data) === 'object'){
        if(JSON.stringify(data) === '{}' || JSON.stringify(data) === '[]'){
            return true;
        }else if(!data){
            return true;
        }
        return false;
    }else if(typeof(data) === 'string'){
        if(!data.trim()){
            return true;
        }
        return false;
    }else if(typeof(data) === 'undefined'){
        return true;
    }else{
        return false;
    }
}

Use cases and results.

console.log(isEmpty()); // true
console.log(isEmpty(null)); // true
console.log(isEmpty('')); // true
console.log(isEmpty('  ')); // true
console.log(isEmpty(undefined)); // true
console.log(isEmpty({})); // true
console.log(isEmpty([])); // true
console.log(isEmpty(0)); // false
console.log(isEmpty('Hey')); // false
只是我以为 2024-07-13 06:20:15

我对如果将非字符串和非空/空值传递给测试器函数会发生什么进行了一些研究。 正如许多人所知, (0 == "") 在 JavaScript 中是正确的,但由于 0 是一个值而不是空或 null,因此您可能需要测试它。

以下两个函数仅对于未定义、null、空/空白值返回 true,对于其他所有值(例如数字、布尔值、对象、表达式等)返回 false。

function IsNullOrEmpty(value)
{
    return (value == null || value === "");
}
function IsNullOrWhiteSpace(value)
{
    return (value == null || !/\S/.test(value));
}

存在更复杂的示例,但这些示例很简单并且给出一致的结果。 无需测试未定义,因为它包含在 (value == null) 检查中。 您还可以通过将它们添加到 String 来模仿 C# 行为,如下所示

String.IsNullOrEmpty = function (value) { ... }

:想要将其放入 Strings 原型中,因为如果 String 类的实例为 null,则会出错:

String.prototype.IsNullOrEmpty = function (value) { ... }
var myvar = null;
if (1 == 2) { myvar = "OK"; } // Could be set
myvar.IsNullOrEmpty(); // Throws error

我使用以下值数组进行了测试。 如果有疑问,您可以循环它来测试您的功能。

// Helper items
var MyClass = function (b) { this.a = "Hello World!"; this.b = b; };
MyClass.prototype.hello = function () { if (this.b == null) { alert(this.a); } else { alert(this.b); } };
var z;
var arr = [
// 0: Explanation for printing, 1: actual value
    ['undefined', undefined],
    ['(var) z', z],
    ['null', null],
    ['empty', ''],
    ['space', ' '],
    ['tab', '\t'],
    ['newline', '\n'],
    ['carriage return', '\r'],
    ['"\\r\\n"', '\r\n'],
    ['"\\n\\r"', '\n\r'],
    ['" \\t \\n "', ' \t \n '],
    ['" txt \\t test \\n"', ' txt \t test \n'],
    ['"txt"', "txt"],
    ['"undefined"', 'undefined'],
    ['"null"', 'null'],
    ['"0"', '0'],
    ['"1"', '1'],
    ['"1.5"', '1.5'],
    ['"1,5"', '1,5'], // Valid number in some locales, not in JavaScript
    ['comma', ','],
    ['dot', '.'],
    ['".5"', '.5'],
    ['0', 0],
    ['0.0', 0.0],
    ['1', 1],
    ['1.5', 1.5],
    ['NaN', NaN],
    ['/\S/', /\S/],
    ['true', true],
    ['false', false],
    ['function, returns true', function () { return true; } ],
    ['function, returns false', function () { return false; } ],
    ['function, returns null', function () { return null; } ],
    ['function, returns string', function () { return "test"; } ],
    ['function, returns undefined', function () { } ],
    ['MyClass', MyClass],
    ['new MyClass', new MyClass()],
    ['empty object', {}],
    ['non-empty object', { a: "a", match: "bogus", test: "bogus"}],
    ['object with toString: string', { a: "a", match: "bogus", test: "bogus", toString: function () { return "test"; } }],
    ['object with toString: null', { a: "a", match: "bogus", test: "bogus", toString: function () { return null; } }]
];

I did some research on what happens if you pass a non-string and non-empty/null value to a tester function. As many know, (0 == "") is true in JavaScript, but since 0 is a value and not empty or null, you may want to test for it.

The following two functions return true only for undefined, null, empty/whitespace values and false for everything else, such as numbers, Boolean, objects, expressions, etc.

function IsNullOrEmpty(value)
{
    return (value == null || value === "");
}
function IsNullOrWhiteSpace(value)
{
    return (value == null || !/\S/.test(value));
}

More complicated examples exists, but these are simple and give consistent results. There is no need to test for undefined, since it's included in (value == null) check. You may also mimic C# behaviour by adding them to String like this:

String.IsNullOrEmpty = function (value) { ... }

You do not want to put it in Strings prototype, because if the instance of the String-class is null, it will error:

String.prototype.IsNullOrEmpty = function (value) { ... }
var myvar = null;
if (1 == 2) { myvar = "OK"; } // Could be set
myvar.IsNullOrEmpty(); // Throws error

I tested with the following value array. You can loop it through to test your functions if in doubt.

// Helper items
var MyClass = function (b) { this.a = "Hello World!"; this.b = b; };
MyClass.prototype.hello = function () { if (this.b == null) { alert(this.a); } else { alert(this.b); } };
var z;
var arr = [
// 0: Explanation for printing, 1: actual value
    ['undefined', undefined],
    ['(var) z', z],
    ['null', null],
    ['empty', ''],
    ['space', ' '],
    ['tab', '\t'],
    ['newline', '\n'],
    ['carriage return', '\r'],
    ['"\\r\\n"', '\r\n'],
    ['"\\n\\r"', '\n\r'],
    ['" \\t \\n "', ' \t \n '],
    ['" txt \\t test \\n"', ' txt \t test \n'],
    ['"txt"', "txt"],
    ['"undefined"', 'undefined'],
    ['"null"', 'null'],
    ['"0"', '0'],
    ['"1"', '1'],
    ['"1.5"', '1.5'],
    ['"1,5"', '1,5'], // Valid number in some locales, not in JavaScript
    ['comma', ','],
    ['dot', '.'],
    ['".5"', '.5'],
    ['0', 0],
    ['0.0', 0.0],
    ['1', 1],
    ['1.5', 1.5],
    ['NaN', NaN],
    ['/\S/', /\S/],
    ['true', true],
    ['false', false],
    ['function, returns true', function () { return true; } ],
    ['function, returns false', function () { return false; } ],
    ['function, returns null', function () { return null; } ],
    ['function, returns string', function () { return "test"; } ],
    ['function, returns undefined', function () { } ],
    ['MyClass', MyClass],
    ['new MyClass', new MyClass()],
    ['empty object', {}],
    ['non-empty object', { a: "a", match: "bogus", test: "bogus"}],
    ['object with toString: string', { a: "a", match: "bogus", test: "bogus", toString: function () { return "test"; } }],
    ['object with toString: null', { a: "a", match: "bogus", test: "bogus", toString: function () { return null; } }]
];
成熟稳重的好男人 2024-07-13 06:20:15
  1. 检查var a;是否存在

  2. 删除值中的错误空格,然后测试是否为空

     if ((a)&(a.trim()!='')) 
       { 
         // 如果变量a不为空则执行此操作  
       } 
      
  1. check that var a; exist

  2. trim out the false spaces in the value, then test for emptiness

     if ((a)&&(a.trim()!=''))
     {
       // if variable a is not empty do this 
     }
    
纸短情长 2024-07-13 06:20:15

我通常使用这样的东西,

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

I usually use something like this,

if (!str.length) {
    // Do something
}
裂开嘴轻声笑有多痛 2024-07-13 06:20:15

另外,如果您将空格填充的字符串视为“空”。

您可以使用以下正则表达式来测试它:

!/\S/.test(string); // Returns true if blank.

Also, in case you consider a whitespace filled string as "empty".

You can test it with this regular expression:

!/\S/.test(string); // Returns true if blank.
糖粟与秋泊 2024-07-13 06:20:15

如果不仅需要检测空字符串,还需要检测空字符串,我将添加到 Goral 的答案中:

function isEmpty(s){
    return !s.length;    
}

function isBlank(s){
    return isEmpty(s.trim());    
}

If one needs to detect not only empty but also blank strings, I'll add to Goral's answer:

function isEmpty(s){
    return !s.length;    
}

function isBlank(s){
    return isEmpty(s.trim());    
}
谢绝鈎搭 2024-07-13 06:20:15

从以下开始:

return (!value || value == undefined || value == "" || value.length == 0);

查看最后一个条件,如果 value == "",则其长度必须为0。因此丢弃它:

return (!value || value == undefined || value == "");

但是等等! 在 JavaScript 中,空字符串为 false。 因此, drop value == "":

return (!value || value == undefined);

并且 !undefined 为 true,因此不需要检查。 所以我们有:

return (!value);

我们不需要括号:

return !value

Starting with:

return (!value || value == undefined || value == "" || value.length == 0);

Looking at the last condition, if value == "", its length must be 0. Therefore drop it:

return (!value || value == undefined || value == "");

But wait! In JavaScript, an empty string is false. Therefore, drop value == "":

return (!value || value == undefined);

And !undefined is true, so that check isn't needed. So we have:

return (!value);

And we don't need parentheses:

return !value
夜灵血窟げ 2024-07-13 06:20:15

我使用组合,最快的检查是最先的。

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

I use a combination, and the fastest checks are first.

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);
}
半衬遮猫 2024-07-13 06:20:15

我没有注意到考虑到字符串中空字符可能性的答案。 例如,如果我们有一个空字符串:

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

要测试它的空性,可以执行以下操作:

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

它适用于空字符串,并且适用于空字符串,并且所有字符串都可以访问它。 此外,它还可以扩展为包含其他 JavaScript 空字符或空白字符(即不间断空格、字节顺序标记、行/段落分隔符等)。

I have not noticed an answer that takes into account the possibility of null characters in a string. For example, if we have a null character string:

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

To test its nullness one could do something like this:

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

It works on a null string, and on an empty string and it is accessible for all strings. In addition, it could be expanded to contain other JavaScript empty or whitespace characters (i.e. nonbreaking space, byte order mark, line/paragraph separator, etc.).

白云悠悠 2024-07-13 06:20:15

您还可以使用正则表达式:

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

检查是否为空或填充空格的字符串。

You could also go with regular expressions:

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

Checks for strings that are either empty or filled with whitespace.

云之铃。 2024-07-13 06:20:15

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

毫无疑问,对于快速而简单的实现,获胜者是: if (!str.length) {...}

但是,还有许多其他示例可用。 我建议最好的功能方法:

function empty(str)
{
    if (typeof str == 'undefined' || !str || str.length === 0 || str === "" || !/[^\s]/.test(str) || /^\s*$/.test(str) || str.replace(/\s/g,"") === "")
        return true;
    else
        return false;
}

我知道,有点过分了。

A lot of answers, and a lot of different possibilities!

Without a doubt for quick and simple implementation the winner is: if (!str.length) {...}

However, as many other examples are available. The best functional method to go about this, I would suggest:

function empty(str)
{
    if (typeof str == 'undefined' || !str || str.length === 0 || str === "" || !/[^\s]/.test(str) || /^\s*$/.test(str) || str.replace(/\s/g,"") === "")
        return true;
    else
        return false;
}

A bit excessive, I know.

怎言笑 2024-07-13 06:20:15

我在这里没有看到一个好的答案(至少没有一个适合我的答案)

所以我决定回答自己:

value === undefined || 值 === null || value === "";

您需要开始检查它是​​否未定义。 否则你的方法可能会爆炸,然后你可以检查它是否等于 null 或者等于空字符串。

你不能有! 或仅 if(value) 因为如果您检查 0 它会给您一个错误的答案(0 是错误的)。

话虽如此,将其包装在如下方法中:

public static isEmpty(value: any): boolean {
返回值===未定义|| 值 === null || 值===“”;
PS

.: 你不需要检查 typeof,因为它甚至在进入方法之前就会爆炸并抛出

I didn't see a good answer here (at least not an answer that fits for me)

So I decided to answer myself:

value === undefined || value === null || value === "";

You need to start checking if it's undefined. Otherwise your method can explode, and then you can check if it equals null or is equal to an empty string.

You cannot have !! or only if(value) since if you check 0 it's going to give you a false answer (0 is false).

With that said, wrap it up in a method like:

public static isEmpty(value: any): boolean {
return value === undefined || value === null || value === "";
}

PS.: You don't need to check typeof, since it would explode and throw even before it enters the method

就像说晚安 2024-07-13 06:20:15

尝试这个:

export const isEmpty = string => (!string || !string.length);

Try this:

export const isEmpty = string => (!string || !string.length);
时光暖心i 2024-07-13 06:20:15

所有这些答案都很好。

但我不能确定该变量是一个字符串,不仅仅包含空格(这对我来说很重要),并且可以包含“0”(字符串)。

我的版本:

function empty(str){
    return !str || !/[^\s]+/.test(str);
}

empty(null); // true
empty(0); // true
empty(7); // false
empty(""); // true
empty("0"); // false
empty("  "); // true

jsfiddle 上的示例。

All these answers are nice.

But I cannot be sure that variable is a string, doesn't contain only spaces (this is important for me), and can contain '0' (string).

My version:

function empty(str){
    return !str || !/[^\s]+/.test(str);
}

empty(null); // true
empty(0); // true
empty(7); // false
empty(""); // true
empty("0"); // false
empty("  "); // true

Sample on jsfiddle.

羁〃客ぐ 2024-07-13 06:20:15

使用空合并运算符修剪空白:

if (!str?.trim()) {
  // do something...
}

Trimming whitespace with the null-coalescing operator:

if (!str?.trim()) {
  // do something...
}
安静 2024-07-13 06:20:15

没有 isEmpty() 方法,您必须检查类型和长度:

if (typeof test === 'string' && test.length === 0){
  ...

需要进行类型检查,以避免当 test 未定义时出现运行时错误 或 null

There's no isEmpty() method, you have to check for the type and the length:

if (typeof test === 'string' && test.length === 0){
  ...

The type check is needed in order to avoid runtime errors when test is undefined or null.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文