JS 数据类型
更新: 2025/3/18 14:37:35 字数: 0 字
一、JS 数据类型
原始类型: null
、undefined
、number
、string
、boolean
、Symbol
、BitInt
。
引用类型: Object
。
二、如何判断 JS 数据类型
typeof
typeof
可以用来确定一个值的基本数据操作类型,用于返回一个数据类型的字符串。
ts
typeof 42; // "number"
typeof true; // "boolean"
typeof "Helloe"; // "string"
typeof null; // "object"
typeof function a(){} // "function"
// 注意
// 1. null 的历史遗留问题
typeof null; // "object"
// 2. new 这些对象也是
typeof new Boolean() // "object"
typeof new String() // "object"
typeof new Number() // "object"
instanceof
instanceof
用于检测构造函数的prototype属性是否出现在某个实例对象的原型链上。
同时属于多个类型,new String()
同时属于 String
和 Object
类型。
ts
const a = new String()
console.log(a instanceof String) // true
console.log(a instanceof Object) // true
// 判断
function Person(){}
var person = new Person()
console.log(person instanceof Person); // true
constructor
通过构造方法来判断类型,主要用于判断对象。
js
function Person(){}
var person = new Person()
console.log(person.constructor) // [Function: Person]
let str = "123"
console.log(str.constructor) // [Function: String]
Object.prototype.toString.call()
[准确]
三、typeof 和 instanceof 区别
typeof
适用于基本数据类型和function
类型的判断,对于原始数据类型(如字符串、数值、布尔值)和函数类型,typeof
可以区分出它们的类型,但对于其他数据类型,通过typeof
只能返回"object"
。instanceof
适用于判断对象的具体类型,它可以判断某个对象是否属于某个特定的构造函数或类的实例,但对于原始数据类型则无法判断。
四、强制类型转换、隐式类型转换
- 强制类型转换:通过
Number()
、String()
、Boolean()
等函数进行类型转换。
js
var num = Number("42"); // 强制将字符串转换为数字
var str = String(123); //强制将数字转换为字符串
var bool = Boolean(O); // 强制将数字转换为布尔值
- 隐式类型转换:当 JavaScript 引擎在遇到一些操作时,会自动进行类型转换,以适应操作的语义。
js
var result = 10 + "5";//隐式将数字和字符串相加,结果为字符串"105"
true == 1; // 隐式将布尔值转换为数字1
false == 0; // 隐式将布尔值转换为数字 0