如何确定变量是'undefined'还是'null'?
How do I determine if variable is undefined
or null
? My code is as follows:
var EmpName = $("div#esd-names div#name").attr('class');
if(EmpName == 'undefined'){
//DO SOMETHING
};
<div id="esd-names">
<div id="name"></div>
</div>
But if I do this, the JavaScript interpreter halts execution.
转载于:https://stackoverflow.com/questions/2647867/how-to-determine-if-variable-is-undefined-or-null
You can use the qualities of the abstract equality operator to do this:
if (variable == null){
// your code here.
}
Because null == undefined
is true, the above code will catch both null
and undefined
.
jQuery attr()
function returns either a blank string or the actual value (and never null
or undefined
). The only time it returns undefined
is when your selector didn't return any element.
So you may want to test against a blank string. Alternatively, since blank strings, null and undefined are false-y, you can just do this:
if (!EmpName) { //do something }
if (variable == null) {
// Do stuff, will only match null or undefined, this won't match false
}
Combining the above answers, it seems the most complete answer would be:
if( typeof variable === 'undefined' || variable === null ){
// Do stuff
}
This should work for any variable that is either undeclared or declared and explicitly set to null or undefined. The boolean expression should evaluate to false for any declared variable that has an actual non-null value.
I've just had this problem i.e. checking if an object is null.
I simply use this:
if (object) { Somecode}
i.e.
if (document.getElementById("enterJob"))
document.getElementById("enterJob").className += ' current';
The standard way to catch null
and undefined
simultaneously is this:
if (variable == null) {
// do something
}
--which is 100% equivalent to the more explicit but less concise:
if (variable === undefined || variable === null) {
// do something
}
When writing professional JS, it's taken for granted that type equality and the behavior of ==
vs ===
is understood. Therefore we use ==
and only compare to null
.
Edit again
The comments suggesting the use of typeof
are simply wrong. Yes, my solution above will cause a ReferenceError if the variable doesn't exist. This is a good thing. This ReferenceError is desirable: it will help you find your mistakes and fix them before you ship your code, just like compiler errors would in other languages.
You should not have any references to undeclared variables in your code.
If the variable you want to check is a global, do
if (window.yourVarName) {
// Your code here
}
This way to check will not throw an error even if the yourVarName
variable doesn't exist.
Example: I want to know if my browser supports History API
if (window.history) {
history.back();
}
How this works:
window
is an object which holds all global variables as its properties, and in JavaScript it is legal to try to access a non-existing object property. If history
doesn't exist then window.history
returns undefined
. undefined
is falsey, so code in an if(undefined){}
block won't run.
Calling typeof null returns a value of “object”, as the special value null is considered to be an empty object reference. Safari through version 5 and Chrome through version 7 have a quirk where calling typeof on a regular expression returns “function” while all other browsers return “object”.
Since you are using jQuery, you can determine whether a variable is undefined or its value is null by using a single function.
var s; // undefined
jQuery.isEmptyObject(s); // will return true;
s = null; // defined as null
jQuery.isEmptyObject(s); // will return true;
// usage
if(jQuery.isEmptyObject(s)){
alert('Either variable: s is undefined or its value is null');
}else{
alert('variable: s has value ' + s);
}
s = 'something'; // defined with some value
jQuery.isEmptyObject(s); // will return false;
if (typeof EmpName != 'undefined' && EmpName) {
will evaluate to true if value is not:
null
undefined
NaN
empty string ("")
0
false
var x;
if (x === undefined) {
alert ("only declared, but not defined.")
};
if (typeof y === "undefined") {
alert ("not even declared.")
};
You can only use second one: as it will check for both definition and declaration
I've come to write my own function for this... javascript is weird
Usable on literally anything. (Note that this also checks if the variable contains any usable values. But since this information is usually also needed, I think it's worth posting). Please consider leaving a note.
function empty(v) {
let type = typeof v;
if(type === 'undefined') {
return true;
}
if(type=== 'boolean') {
return !v;
}
if(v === null) {
return true;
}
if(v === undefined) {
return true;
}
if(v instanceof Array) {
if(v.length < 1) {
return true;
}
}
else if(type === 'string') {
if(v.length < 1) {
return true;
}
if(v==='0') {
return true;
}
}
else if(type === 'object') {
if(Object.keys(v).length < 1) {
return true;
}
}
else if(type === 'number') {
if(v===0) {
return true;
}
}
return false;
}
Typescript-compatible.
edit. this function should do exactly the same thing like PHPs empty()
function (see RETURN VALUES
)
Considers undefined
, null
, false
, 0
, 0.0
, "0"
{}
, []
as empty.
"0.0"
, NaN
, " "
, true
are considered non-empty.
To test if a variable is null or undefined I use the below code.
if(sVal === '' || sVal === null ||typeof sVal === 'undefined'){
console.log('variable is undefined or null');
}
i run this test on chrome console, using (void 0) you can check undefined
var c;
undefined
if(c === void 0)alert();
// output = undefined
var c = 1;
// output = undefined
if(c === void 0)alert();
// output = undefined
// check c value c
// output = 1
if(c === void 0)alert();
// output = undefined
c = undefined;
// output = undefined
if(c === void 0)alert();
// output = undefined
Best way:
if(typeof variable==='undefined' || variable===null) {
/* do your stuff */
}
var i;
if(i === null || typeof i === 'undefined'){
console.log(i,'i is undefined or null')
}else{
console.log(i,'i has some value')
}
This is a very old question, but I still think the best/safe way to test these 2 conditions are to cast the value to string:
var EmpName = $("div#esd-names div#name").attr('class');
// Undefined check
if (Object.prototype.toString.call(EmpName) === '[object Undefined]'){
// do something with your code
}
// Nullcheck
if (Object.prototype.toString.call(EmpName) === '[object Null]'){
// do something with your code
}
You can check if the value is undefined or null by simply using typeof:
if(typeof value == 'undefined'){
if(x==null)
is bad idea in javascript,judge with "=="
may cause unexpected type coercion, and can't be read by coffee-script,
never use "==" or "!=" in condition judgment!
if(x)
will be better.but becareful 0 and "", it will be treat as false,not equal method with "!= null"
is true.
With the solution below:
const getType = (val) => typeof val === 'undefined' || !val ? null : typeof val;
const isDeepEqual = (a, b) => getType(a) === getType(b);
console.log(isDeepEqual(1, 1)); // true
console.log(isDeepEqual(null, null)); // true
console.log(isDeepEqual([], [])); // true
console.log(isDeepEqual(1, "1")); // false
etc...
I'm able to check for the following:
- null
- undefined
- NaN
- empty
- string ("")
- 0
- false
(null == undefined) // true
(null === undefined) // false
Because === checks for both the type and value. Type of both are different but value is the same.
I see that the original post was using JQuery. So I am adding what I have used in the past via JQuery. Usually when I am performing such a check I am not necessarily checking for the value to be null or undefined just for that purpose. More like "Is the value there so I can perform actions on it.". So for that I use the following. I have not tried every type but I know it works for both null and undefined. Also, objects and arrays(empty version of those will return true). Also, of course if the variable does not exist you will get an exception but I honestly try to avoid that at all costs. So I agree with Aerovistae. I want to know about this in my code and don't want to just skip over it.
if ($.trim(value) != '') {
//Do Something
}
In some circumstances it is possible to change the value of undefined
. While these are generally rare, it can sometimes be best to avoid the actual use of the undefined
value.
As a result, and because it is quicker to write, I have become accustomed to using a shortcut for undefined
which is to look at the first value of an empty array. This value is guaranteed to be the primitive value undefined
, and can be accessed with [][0]
.
This check will work to look for both undefined
and null
.
Here is an example:
(function(undefined){
var foo = { baz: null };
console.log(foo.bar === undefined); //false
console.log(foo.bar == [][0]); //true
console.log(foo.baz == [][0]); //true
}(50))
</div>
You can check it by this method-
if(['object','undefined'].indexOf(typeof(variable)) != -1){
console.log("variable is null or undefined.");
}