JavaScript typeof, null, 和 undefined,以及instanceof

你可以使用 typeof 操作符来检测变量的数据类型。

一、typeof示范代码

typeof "John"                // 返回 string
typeof 3.14                  // 返回 number
typeof false                 // 返回 boolean
typeof [1,2,3,4]             // 返回 object
typeof {name:'John', age:34} // 返回 object

二、在 JavaScript 中 null 表示 "什么都没有"

用 typeof 检测 null 返回是object。

var person = null;           // 值为 null(空), 但类型为对象

三、在 JavaScript 中, undefined 是一个没有设置值的变量

var person;                  // 值为 undefined(空), 类型是undefined
person = undefined;          // 值为 undefined, 类型是undefined

四、undefined 和 null 的区别

null 和 undefined 的值相等,但类型不等:

typeof undefined             // undefined
typeof null                  // object
null === undefined           // false
null == undefined            // true

五、可通过 instanceof 操作符来判断对象的具体类型,语法格式

arr = [1,2,3];
if(arr instanceof Array){
    document.write("arr 是一个数组");
} else {
    document.write("arr 不是一个数组");
}

本文参考:

https://www.runoob.com/js/js-typeof.html

posted @ 2021-07-02 19:32  那些年的事儿  阅读(313)  评论(0编辑  收藏  举报