In JavaScript, you can use the typeof operator and the "==" operator to determine whether the specified value is undefined. The syntax "if (typeof (specified value) == "undefined"){//The value is undefined;}".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Undefined type
Undefined is a special data type with only one value, which means undefined. When we declare a variable but do not assign a value to the variable, the default value of the variable is Undefined. For example:
var num; console.log(num); // 输出 undefined
So how to determine whether the value is undefined?
In JavaScript, you can use the typeof operator to determine whether the value is undefined.
When you use the typeof operator to view unassigned variable types, you will find that their types are also undefined. For undeclared variables, use the typeof operator to check their types and you will find that undeclared variables are also undefined. The sample code is as follows:
var message; console.log(typeof message); // 输出 undefined console.log(typeof name); // 输出 undefined
Judgment method:
var tmp = undefined; if (typeof(tmp) == "undefined"){ alert("值为 undefined"); }
Description: typeof operator
typeof is a unary operator used to return a string of the operand type.
The data type of NaN is number
The data type of array (Array) is object
The data type of date (Date) is object
The data type of null is object
The data type of undefined variables is undefined
typeof [1, 2, 3, 5]; // 返回object typeof new Date(); // 返回 object typeof NaN; // 返回 number typeof function () {} // 返回 function typeof myCar; // 返回 undefined (如果 myCar 没有声明)
The difference between undefined and null:
typeof null; // 返回object typeof undefined; // 返回undefined null === undefined; //false null == undefined; // true
[Related recommendations: javascript learning tutorial]
The above is the detailed content of How to determine whether a value is undefined in javascript. For more information, please follow other related articles on the PHP Chinese website!