是否有标准函数来检查 JavaScript 中的 null、未定义或空白变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5515310/
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 a standard function to check for null, undefined, or blank variables in JavaScript?
提问by Alex
Is there a universal JavaScript function that checks that a variable has a value and ensures that it's not undefined
or null
? I've got this code, but I'm not sure if it covers all cases:
是否有一个通用的 JavaScript 函数来检查变量是否具有值并确保它不是undefined
或null
?我有这个代码,但我不确定它是否涵盖所有情况:
function isEmpty(val){
return (val === undefined || val == null || val.length <= 0) ? true : false;
}
回答by jAndy
You can just check if the variablehas a truthy
value or not. That means
您可以只检查变量是否有truthy
值。这意味着
if( value ) {
}
will evaluate to true
if value
is not:
将评估为true
if value
is not:
- null
- undefined
- NaN
- empty string ("")
- 0
- false
- 空值
- 不明确的
- NaN
- 空字符串 ("")
- 0
- 错误的
The above list represents all possible falsy
values in ECMA-/Javascript. Find it in the specificationat the ToBoolean
section.
上面的列表代表falsy
了 ECMA-/Javascript 中所有可能的值。在部分的规范中找到它ToBoolean
。
Furthermore, if you do not knowwhether a variable exists (that means, if it was declared) you should check with the typeof
operator. For instance
此外,如果您不知道变量是否存在(也就是说,如果已声明),您应该检查typeof
操作符。例如
if( typeof foo !== 'undefined' ) {
// foo could get resolved and it's defined
}
If you can be sure that a variableis declared at least, you should directly check if it has a truthy
value like shown above.
如果您可以确定至少声明了一个变量,则应直接检查它是否具有truthy
如上所示的值。
Further read: http://typeofnan.blogspot.com/2011/01/typeof-is-fast.html
进一步阅读:http: //typeofnan.blogspot.com/2011/01/typeof-is-fast.html
回答by Salman A
The verbose method to check if value is undefined or null is:
检查值是否未定义或为空的详细方法是:
return value === undefined || value === null;
You can also use the ==
operator but this expects one to know all the rules:
您也可以使用==
运算符,但这需要知道所有规则:
return value == null; // also returns true if value is undefined
回答by Mike Samuel
function isEmpty(value){
return (value == null || value.length === 0);
}
This will return true for
这将返回 true
undefined // Because undefined == null
null
[]
""
and zero argument functions since a function's length
is the number of declared parameters it takes.
和零参数函数,因为函数length
是它所采用的声明参数的数量。
To disallow the latter category, you might want to just check for blank strings
要禁止后一类,您可能只想检查空白字符串
function isEmpty(value){
return (value == null || value === '');
}
回答by guya
This is the safest check and I haven't seen it posted here exactly like that:
这是最安全的检查,我还没有看到它完全像这样发布在这里:
if (typeof value !== 'undefined' && value) {
//deal with value'
};
It will cover cases where valuewas never defined, and also any of these:
它将涵盖从未定义值的情况,以及以下任何一种情况:
- null
- undefined (value of undefined is not the same as a parameter that was never defined)
- 0
- "" (empty string)
- false
- NaN
- 空值
- 未定义(未定义的值与从未定义的参数不同)
- 0
- ""(空字符串)
- 错误的
- NaN
Edited: Changed to strict equality (!==) because it's the norm by now ;)
编辑:更改为严格相等(!==),因为它现在是规范;)
回答by Vix
You may find the following function useful:
您可能会发现以下功能很有用:
function typeOf(obj) {
return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
}
Or in ES7 (comment if further improvements)
或者在 ES7 中(如果有进一步改进请评论)
function typeOf(obj) {
const { toString } = Object.prototype;
const stringified = obj::toString();
const type = stringified.split(' ')[1].slice(0, -1);
return type.toLowerCase();
}
Results:
结果:
typeOf(); //undefined
typeOf(null); //null
typeOf(NaN); //number
typeOf(5); //number
typeOf({}); //object
typeOf([]); //array
typeOf(''); //string
typeOf(function () {}); //function
typeOf(/a/) //regexp
typeOf(new Date()) //date
typeOf(new WeakMap()) //weakmap
typeOf(new Map()) //map
"Note that the bind operator (::) is not part of ES2016 (ES7) nor any later edition of the ECMAScript standard at all. It's currently a stage 0 (strawman) proposal for being introduced to the language." – Simon Kjellberg. the author wishes to add his support for this beautiful proposal to receive royal ascension.
“请注意,绑定运算符 (::) 不是 ES2016 (ES7) 的一部分,也不是 ECMAScript 标准的任何更高版本。它目前是引入该语言的第 0 阶段(稻草人)提案。” – 西蒙·凯尔伯格。作者希望支持这项美丽的升职提议。
回答by krupar
The first answer with best rating is wrong. If value is undefined it will throw an exception in modern browsers. You have to use:
评分最高的第一个答案是错误的。如果 value 未定义,它将在现代浏览器中引发异常。你必须使用:
if (typeof(value) !== "undefined" && value)
or
或者
if (typeof value !== "undefined" && value)
回答by Arif
!check for empty strings (""), null, undefined, false and the number 0 and NaN.Say, if a string is empty var name = ""
then console.log(!name)
returns true
.
!检查空字符串 ("")、null、undefined、false 以及数字 0 和 NaN。比如说,如果一个字符串为空,var name = ""
则console.log(!name)
返回true
.
function isEmpty(val){
return !val;
}
this function will return true if valis empty, null, undefined, false, the number 0 or NaN.
如果val为空、null、undefined、false、数字 0 或 NaN,则此函数将返回 true 。
OR
或者
According to your problem domain you can just use like !val
or !!val
.
根据您的问题域,您可以使用 like!val
或!!val
。
回答by JerryP
This condition check
这个条件检查
if (!!foo) {
//foo is defined
}
is all you need.
是你所需要的全部。
回答by Alexandre Magro
A solution I like a lot:
我非常喜欢的一个解决方案:
Let's define that a blank variable is null
, or undefined
, or if it has length, it is zero, or if it is an object, it has no keys:
让我们定义一个空白变量是null
, or undefined
,或者如果它有长度,它为零,或者如果它是一个对象,它没有键:
function isEmpty (value) {
return (
// null or undefined
(value == null) ||
// has length and it's zero
(value.hasOwnProperty('length') && value.length === 0) ||
// is an Object and has no keys
(value.constructor === Object && Object.keys(value).length === 0)
)
}
Returns:
返回:
- true:
undefined
,null
,""
,[]
,{}
- false:
true
,false
,1
,0
,-1
,"foo"
,[1, 2, 3]
,{ foo: 1 }
- 真:
undefined
,null
,""
,[]
,{}
- 假:
true
,false
,1
,0
,-1
,"foo"
,[1, 2, 3]
,{ foo: 1 }
回答by tcooc
You are a bit overdoing it. To check if a variable is not given a value, you would only need to check against undefined and null.
你有点过分了。要检查变量是否没有赋值,您只需要检查 undefined 和 null。
function isEmpty(value){
return (typeof value === "undefined" || value === null);
}
This is assuming 0
, ""
, and objects(even empty object and array) are valid "values".
这是假设0
,""
和 对象(甚至空对象和数组)是有效的“值”。