JavaScript typeof, null, undefined

本章我们将学习 JavaScript 中的 typeofnullundefinedvalueOf()


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中,数组是一种特殊的对象类型,因此 typeof [1,2,3,4] 返回 object


null

null 关键字用于表示 "什么都没有"

null 是一个只有一个值的特殊类型,表示一个空对象引用

用 typeof 检测 null 返回是 object

可以将一个变量设置为 null 来清空

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

同时也可以设置为 undefined 来清空对象

var person = undefined;  // 值为 undefined, 类型为 undefined


undefined

undefined 是一个没有设置值的变量

typeof 一个没有值的变量会返回 undefined

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

任何变量都可以通过设置值为 undefined 来清空

person = undefined;   // 值为 undefined, 类型是 undefined


undefined 和 null 的区别

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

typeof undefined  // undefined
typeof null       // object

null === undefined  // false
null == undefined   // true

本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!

链接: https://fly63.com/course/7_488

目录选择