Javascript javascript中有没有像string.isnullorempty()这样的函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3977988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:59:40  来源:igfitidea点击:

is there any function like string.isnullorempty() in javascript

javascriptjquerynullundefined

提问by uzay95

I always (thing != undefined || thing != null)?...:...;check. Is there any method will return bool after this check in javascript or jquery ?

我总是(thing != undefined || thing != null)?...:...;检查。在 javascript 或 jquery 中进行此检查后,是否有任何方法会返回 bool ?

And how would you add this check in jquery as a function?

你将如何在 jquery 中添加这个检查作为一个函数?

回答by femseks

if (thing)
{
   //your code
}

Is that what you are looking for?

这就是你要找的吗?

回答by SLaks

In Javascript, the values null, undefined, "", 0, NaN, and falseare all "falsy" and will fail a conditional.
All other values are "truthy" and will pass a conditional.

在 Javascript 中,值null, undefined, "", 0, NaN, 和false都是“假的”并且会在条件下失败。
所有其他值都是“真实的”并且会传递一个条件。

Therefore, you can simply write thing ? ... : ....

因此,您可以简单地编写 thing ? ... : ....

回答by Developer Dave

As the others here have mentioned, several things evaluate as "falsy" that you might not want to (such as empty strings or zero). The simplest way I've found in JavaScript to check for both nulland undefinedin one statement is:

正如这里的其他人所提到的,有几件事被评估为您可能不想要的“假”(例如空字符串或零)。我在 JavaScript 中找到的在一个语句中同时检查null和检查的最简单方法undefined是:

thing != null

This is using type coercion (double equals instead of triple equals), so undefined values are coerced to nullhere, while empty strings, zero, etc. do not.

这是使用类型强制(双等号而不是三等号),因此未定义的值被强制到null这里,而空字符串、零等不会。

回答by i_thamary

Try this

尝试这个

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