JS有八种内置类型:
- 空置 null
- 未定义 undefined
- 布尔值 boolean
- 数字 number
- 字符串 string
- 对象 object
- 符号 symbol ES6新增的
- 大整数 bigint ES6新增的
typeof undefined === "undefined"; // true
typeof true === "boolean"; // true
typeof 42 === "number"; // true
typeof "42" === "string"; // true
typeof { life: 42 } === "object"; // true
// ES6中新加入的类型
typeof Symbol() === "symbol"; // true
typeof BigInt(1) === "bigint"; // true
但是 null类型比较特殊
typeof null === “object”; // true
这是由于历史原因所导致,这里不做解释。
不知道你是否尝试过 typeof function a() {} === “function” ;// true
难道function也是js的内置类型?
其实并不是,它只是object的一个“子类型”。具体来说,函数是“可调用对象”,它有一个内部属性[[Call]],该属性使其可以被调用。
另外,函数不仅是对象,而且还拥有属性。例如:
function test (a, b, c) {}
test.length; // 3
因为此函数声明了3个命名参数a, b, c,所以其length值为3。
类似地,数组也只是object的一个“子类型”
typeof [1, 2, 3] === "object"; // true
undefined 和 undeclared
undefined和undeclared是完全不一样的;
undefined: 变量已声明但未赋值
undeclared: 变量未声明
var a;
a;// undefined
b; // ReferenceError: b is not defined
但是如果我们typeof的话,它们的返回值都是undefined。有点恶心
typeof a; // undefined
typeof b; // undefined
此外,在非严格模式下,undefined可以被当作变量来使用和赋值
function foo () {
undefined = 2;
}
foo();
function foo () {
"use strict";
undefined = 2; // TypeError
}
有时候,我们需要一个undefined作为返回结果,那么怎么获取安全的undefined呢?
void 运算符
表达式 void _ 没有返回值,因此返回结果是undefined。void并不是改变表达式的结果,只是让表达式不返回值。
var a = 1;
console.log(void a, a); // undefined 42