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
is there any function like string.isnullorempty() in javascript
提问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 false
are 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 null
and undefined
in 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 null
here, while empty strings, zero, etc. do not.
这是使用类型强制(双等号而不是三等号),因此未定义的值被强制到null
这里,而空字符串、零等不会。
回答by i_thamary
Try this
尝试这个
function SringisEmpty(str) {
str=str.trim();
return (!str || 0 === str.length);
}