javascript怎么判断值是否为undefined
时间:2022-02-23 17:38
在javascript中,可以利用typeof操作符和“==”运算符来判断指定值是否为undefined,语法“if (typeof(指定值) == "undefined"){//值为undefined;}”。 本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。 Undefined 类型 Undefined 是一个只有一个值的特殊数据类型,表示未定义。当我们声明一个变量但未给变量赋值时,这个变量的默认值就是 Undefined。例如: 那么怎么判断值是否为undefined? 在javascript中,可以利用typeof 操作符来判断值是否为undefined。 在使用 typeof 操作符查看未赋值的变量类型时,会发现它们的类型也是 undefined。对于未声明的变量,使用 typeof 操作符查看其类型会发现,未声明的变量也是 undefined,示例代码如下: 判断方法: 说明:typeof 操作符 typeof是一元运算符,用来返回操作数类型的字符串。 NaN 的数据类型是 number 数组(Array)的数据类型是 object 日期(Date)的数据类型为 object null 的数据类型是 object 未定义变量的数据类型为 undefined undefined 和 null 的区别: 【相关推荐:javascript学习教程】 以上就是javascript怎么判断值是否为undefined的详细内容,更多请关注gxlsystem.com其它相关文章!var num;
console.log(num); // 输出 undefined
var message;
console.log(typeof message); // 输出 undefined
console.log(typeof name); // 输出 undefined
var tmp = undefined;
if (typeof(tmp) == "undefined"){
alert("值为 undefined");
}
typeof [1, 2, 3, 5]; // 返回object
typeof new Date(); // 返回 object
typeof NaN; // 返回 number
typeof function () {} // 返回 function
typeof myCar; // 返回 undefined (如果 myCar 没有声明)
typeof null; // 返回object
typeof undefined; // 返回undefined
null === undefined; //false
null == undefined; // true