总结一下js中数据类型的相关内容
首先我们可以将数据类型分为两大类 基础数据类型 和 引用(复杂)数据类型
基础数据类型有以下几种:
Number、String、Boolean、Null、undefined、symbol、bigInt,其中symbol和bigInt为es6新增。
引用数据类型有以下几种:
function(函数)、Array(数组)、Object(对象)
针对不同的数据类型,当我们遇到时如果不知道其真正的数据类型就无法使用正确的方法进行处理,因此,也就有了不同的检测方法。
方法一:typeof
用typeof检测后的返回值为字符串,但这种方式检测存在弊端,就是无法检测复杂的引用类型数据,当我们用typeof去检测对象、数组、函数后,会返回object,很显然这种方式不是我们所期待的,因此针对简单的基础数据类型检测,推荐使用typeof。
方法二:instanceof
instanceof
是 JavaScript 中用于检查一个对象是否是某个特定类或构造函数的实例的操作符。它的语法形式是 object instanceof constructor
。
class Person {
constructor(name) {
this.name = name;
}
}
const john = new Person('John');
console.log(john instanceof Person); // 输出: true
console.log(john instanceof Object); // 输出: true
console.log(john instanceof Array); // 输出: false
instanceof返回的是一个布尔值,这种方式同样存在弊端,就是针对简单的基础数据类型的检测不明确,所以instanceof多用来判断复杂的引用数据类型。
方法三:constructor
每个 JavaScript 对象都有一个 constructor
属性,它引用创建该对象的构造函数。判断后返回的值仍然为布尔值,但是对基础数据类型也可以判断
class Person {
constructor(name) {
this.name = name;
}
}
const john = new Person('John');
const str = 'Hello, World!';
const num = 42;
const arr = [1, 2, 3];
console.log(john.constructor === Person); // 输出: true
console.log(str.constructor === String); // 输出: true
console.log(num.constructor === Number); // 输出: true
console.log(arr.constructor === Array); // 输出: true
方法四:Object.prototype.toString.call()
Object.prototype.toString.call()
是用于获取对象的类型信息的常见方法。它基于对象的 toString()
方法,通过调用该方法并传入要检查的对象作为 this
值,然后使用 call()
方法来改变 this
的上下文。
使用 Object.prototype.toString.call()
方法可以判断对象的数据类型,包括原始数据类型、内置对象和自定义对象等。
需要注意的是,返回的类型信息是一个以 [object 类型]
形式表示的字符串。例如,Object.prototype.toString.call(john)
返回的是 [object Object]
,而不仅仅是 Object
。这是因为 toString()
方法被所有对象继承,并且它的行为基于每个对象的内部 [[Class]]
属性。
const john = {
name: 'John',
};
console.log(Object.prototype.toString.call(john)); // 输出: [object Object]
const str = 'Hello, World!';
console.log(Object.prototype.toString.call(str)); // 输出: [object String]
const num = 42;
console.log(Object.prototype.toString.call(num)); // 输出: [object Number]
const arr = [1, 2, 3];
console.log(Object.prototype.toString.call(arr)); // 输出: [object Array]