8种数据类型
js有8种数据类型, 其中6种为原始类型和2种为Object类型
6种原始类型
- Number: typeof instance === “number”
- Boolean: typeof instance === “boolean”
- String: typeof instance === “string”
- BigInt: typeof instance === “bigint”
- undefined: typeof instance === “undefined”
- Symbol: typeof instance === “symbol”
2种Object类型
- null: typeof instance === “object”
- Object: typeof instance === “object” . new Object,new Array,new Map,new Set,new WeakMap,new WeakSet,new Date,和几乎所有通过 new keyword 创建的东西都是 Object类型
undefined 与 null
Null
- null 表示一个"无"的对象,转为数值为 0
- 作为函数的参数,表示该函数的参数不是对象
- 作为对象原型链的终点
- Number(null) 为 0
- 5 + null 为 5;
- JSON.stringify(null) 为 ‘null’ (字符串);
- JSON.parse(null) 为 null (null 基本类型)。
Undefined
- 变量被声明了,但是没有赋值,就等于 undefined;
- 调用函数时,应该提供的参数没有提供,该参数等于 undefined;
- 对象没有赋值属性,该属性的值为 undefined;
- 函数没有返回值时,默认返回 undefined;
- Number(undefined) 为 NaN;
- 5 + undefined 为 NaN;
- JSON.stringify(undefined) 为 undefined;
- JSON.parse(undefined) 为 报错。
未初始化和未定义的变量值都是undefined
undefined + 1
的结果为NaN
let x ;
console.log(typeof x) // undefined
console.log(x+1) // NaN
console.log(typeof (x+1)) // number
null+1
的结果是1
null+undefined
的结果是NaN
NaN与Number
NaN
即 Not a Number
,不是一个数字。 在 JavaScript 中,整数和浮点数都统称为 Number 类型 。除此之外,Number 类型还有一个很特殊的值,即 NaN 。它是 Number 对象上的一个静态属性,可以通过 Number.NaN
来访问
判断是否为NaN: Number.isNaN(变量)