每天学废一个面试题:JS有几种数据类型,其中哪些是基本数据类型?

296 阅读2分钟

这是我参与8月更文挑战的第4天,活动详情查看:8月更文挑战

JS目前共有 8 种数据类型。

7种基本类型

其中 7 种基本类型,除了null外都可使用typeof运算符进行检查:

  1. undefined:已声明未赋值的变量初始值
  2. boolean:布尔值
  3. number:64位双精度浮点型
  4. string:字符串
  5. symbol:符号类型,唯一且不可修改
  6. bigint:任意精度格式的整数
  7. null:空对象

基本类型又叫值类型,值类型的值是始终不变的,比如定义了var a = 1,虽然变量a可以重新赋值,但是1这个值本身是不会变的。

除了nullundefined,其他 5 种基本类型都有对应的包装对象(将基本类型的单词首字母改为大写即为对应包装对象)。

1种引用类型

1 种引用类型Object

在JavaScript中,几乎所有的对象都是Object类型的实例,它们都会从Object.prototype继承属性和方法。

Function、Array、Date以及上面基本类型的包装对象,实际上都是由Object派生的,都属于Object类(用instanceof运算符检测结果为true,如 Function instanceof Object )。

牛刀小试:
// typeof
typeof 1 // number
typeof "1" // string
typeof true // boolean
const a = Symbol(1)
typeof a // symbol
typeof 1n // bigint
typeof null // object(注意此处)
typeof undefined // undefined

typeof String // function
typeof Number // function
typeof Array // function
typeof Date // function
typeof Object // function

// instanceof
String instanceof Function // true
String instanceof Object // true

Function instanceof Object // true
Object instanceof Function // true

// 包装类
new String(1) // "1"
new Number("1") // 1
new Object("1") // "1"
new Object(1) // 1
new Object(String(1)) // "1"
new Object(Number(1)) // 1

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

// 隐式转换
1 == "1" // true
true == "0" // false
true == "1" // true
1 + "1" // "11"
"1" - 1 // 0
0 == "0" // true
1 == "1" // true

参考资料

[1] 语法和数据类型