null,undefined," "的区别, typeof null 和 typeof undefined

此文章只是为了自己方便记忆写的随笔

都知道 JavaScript 数据类型有:字符串值(string),数值(number),布尔值(boolean),数组(arry),对象(object)。

Null
在 JavaScript 中,null 是 “nothing”。它被看做不存在的事物。

不幸的是,在 JavaScript 中,null 的数据类型是对象。

您可以把 null 在 JavaScript 中是对象理解为一个 bug。它本应是 null。

您可以通过设置值为 null 清空对象:

var person = null; // 值是 null,但是类型仍然是对象
typeof null // object

Undefined

在 JavaScript 中,没有值的变量,其值是 undefined。typeof 也返回 undefined。

var person; // 值是 undefined,类型是 undefined
typeof person // undefined

空值

空值与 undefined 不是一回事。

空的字符串变量既有值也有类型。

var car = “”; // 值是 “”,类型是 “string”
typeof car // string

Undefined 与 Null 的区别

*Undefined 与 null 的值相等,但类型不相等:

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

原始数据

原始数据值是一种没有额外属性和方法的单一简单数据值。

typeof 运算符可返回以下原始类型之一:

  • string
  • number
  • boolean
  • undefined

typeof “Bill” // 返回 “string”
typeof 3.14 // 返回 “number”
typeof true // 返回 “boolean”
typeof false // 返回 “boolean”
typeof x // 返回 “undefined” (假如 x 没有值)

复杂数据

typeof 运算符可返回以下两种类型之一:

  • function
  • object

typeof 运算符把对象、数组或 null 返回 object。

typeof 运算符不会把函数返回 object。

typeof {name:‘Bill’, age:62} // 返回 “object”
typeof [1,2,3,4] // 返回 “object” (并非 “array”,参见下面的注释)
typeof null // 返回 “object”
typeof function myFunc(){} // 返回 “function”

你可能感兴趣的:(js)