基本的数据类型介绍,及值类型和引用类型的理解
在 JS 中共有 8 种基础的数据类型,分别为: Undefined 、 Null 、 Boolean 、 Number 、 String 、 Object 、 Symbol 、 BigInt 。
其中 Symbol 和 BigInt 是 ES6 新增的数据类型,可能会被单独问:
Symbol 代表独一无二的值,最大的用法是用来定义对象的唯一属性名。
BigInt 可以表示任意大小的整数。
这些数据可以分为原始数据类型和引用数据类型:
栈:原始数据类型(Undefined、Null、Boolean、Number、String)
堆:引用数据类型(对象、数组和函数)
Js判断数据类型检测的方式有哪些
typeof
其中数组、对象、null都会被判断为object,其他判断都正确,typeof返回的类型都是字符串形式
console.log(typeof undefined); // undefined
console.log(typeof 2); // number
console.log(typeof true); // boolean
console.log(typeof "str"); // string
console.log(typeof Symbol("foo")); // symbol
console.log(typeof 12343343n); // bigint
console.log(typeof function () {}); // function
//不能判别
console.log(typeof []); // object
console.log(typeof {}); // object
console.log(typeof null); // object
instanceof
能判断对象类型,不能判断基本数据类型,其内部运行机制是判断在其原型链中能否找到该类型的原型
const theString = 'String';
const newString = new String('这是 New 出来的 String');
console.log(theStrings instanceof String); // false,检查原型链会返回 undefined,同理用instanceof判断number依旧如此
console.log(newString instanceof String); // true
const theOjbect = {};
const newObject = new Object();
console.log(theOjbect instanceof Object); // true
console.log(newObject instanceof Object); // true
Object.prototype.toString.call()
所有原始数据类型都是能判断的,还有 Error 对象,Date 对象等。
Object.prototype.toString.call(2); // "[object Number]"
Object.prototype.toString.call("123"); // "[object String]"
Object.prototype.toString.call(true); // "[object Boolean]"
Object.prototype.toString.call(undefined); // "[object Undefined]"
Object.prototype.toString.call(null); // "[object Null]"
Object.prototype.toString.call(Math); // "[object Math]"
Object.prototype.toString.call({}); // "[object Object]"
Object.prototype.toString.call([]); // "[object Array]"
Object.prototype.toString.call(function () {}); // "[object Function]"
如何判断变量是否为数组
Array.isArray(arr); // true
arr.__proto__ === Array.prototype; // true
arr instanceof Array; // true
Object.prototype.toString.call(arr); // "[object Array]"