javascript可能会遗忘的知识点回顾

113 阅读1分钟

JavaScript 的基本类型有哪些?引用类型有哪些?null 和 undefined 的区别?

数据类型

基本数据类型:Number、String、Boolean、null、undefined
引用数据类型:Function、Object、Array

区别

undefined:表示变量声明但未初始化时候的值
null:表示准备用来保存对象,还没有真正保存对象的值.从逻辑角度看,null值表示一个空对象指针
ECMA 标准要求null和undefined等值判断返回true
null == undefimed //true
null === undefined //false

如何判断Javascript的数据类型?

判断方法

typeof
typeof可以用来区分除了null类型以外的原始数据类型,对象类型的可以从普通对象里面识别出函数:
typeof undefined //'undefined'
typeof null // 'object'
typeof 1 // 'number'

typeof '1' //'string'
typeof Symbol() // 'symbol'
typeof function(){} // 'function'
typeof {} // 'object'

typeof 不能识别null,如何识别null?

如果想要判断是否weinull,可以直接使用===全等运算符来判断(或者使用下面的 Object.prototype.toString 方法):
let a = null
a === null //true

typeof 作用于未定义的变量,会报错吗?

不会报错,返回'undefined'
typeof randomVariable //'undefined'

typeof Number(1)的返回值是什么?

'Number' Number和String作为普通函数调用的时候,是把参数转化为相应的原始数据类型,也就是类似于做一个强制类型转换的操作,而不是默认当做构造函数调用.注意和Array区分,Array(...)等价于new Array(...)
typeof Number(1) //'number'
typeof String('1') //'string'
Array(1,2,3)//等价于new Array(1,2,3)

typeof new Number(1)的返回值是什么?

'object'
typeof new Number(1) // 'object'
typeof new String(1) // 'object'