JS共有几种数据类型?
8种。Undefined、Null、String、Number、Boolean、Object、Symbol、BigInt
注:1. Symbol:创建后独一无二、不可变的值,为解决全局变量冲突问题(ES6)。2. BigInt:可表示任意精度的整数,可安全存储和操作大数据(谷歌67版本)。
JS中的原始数据类型和引用数据类型分别为哪些?
栈:原始数据类型(Undefined、Null、String、Number、Boolean)
堆:引用数据类型(对象、数组和函数)
注: Object包含null和对象,null值表示一个空对象指针
检测JS数据类型方法有哪些?
- typeof 一元运算,运算数可为任意类型,
typeof NaN // Number
typeof true // Boolean
typeof [] // object
typeof Symbol() // Symbol
typeof BigInt(123456789) // BigInt
- instanceof 仅判断引用数据类型,测试一个对象在其原型链中是否存在一个构造函数的prototype属性
[] instanceof Array // true
function() {} instanceof Function // true
{} instanceof object // true
- constructor 通过constructor对象访问其构造函数
("123").constructor === String // true
(123).constructor === Number // true
([]).constructor === Array // true
(function() {}).constructor === Function // true
({}).constructor === Object // true
注: 1. null和undefined是无效对象,不会有constructor存在,需用其他方式进行判断。2. 改变其构造函数的原型则无法用constructor来判断
- Object.prototype.toString.call() 使用 Object 对象的原型方法 toString 来判断数据类型
var a = Object.prototype.toString;
console.log(a.call(123)); // [object Number]
console.log(a.call(true)); // [object Boolean]
console.log(a.call('str')); // [object String]
console.log(a.call([])); // [object Array]
console.log(a.call(function() {})); // [object Function]
console.log(a.call({})); // [object Object]
console.log(a.call(undefined)); // [object Undefined]
console.log(a.call(null)); // [object Null]