JS的数据类型?如何判断js的数据类型?
时间: 2024-03-20 15:19:03 浏览: 15
JavaScript有七种不同的数据类型:
1. 基本数据类型(Primitive data types):包括字符串(String)、数字(Number)、布尔值(Boolean)、空(Null)、未定义(Undefined)和 Symbol(ES6 新增)。
2. 引用数据类型(Reference data types):包括对象(Object)、数组(Array)和函数(Function)。
判断JavaScript数据类型的方法有很多种,以下是一些常用的方法:
1. typeof运算符:判断基本数据类型
2. instanceof运算符:判断引用数据类型
3. Object.prototype.toString方法:判断基本和引用数据类型
例如:
```
typeof "hello" // "string"
typeof 42 // "number"
typeof true // "boolean"
typeof undefined // "undefined"
typeof null // "object" (!)
typeof Symbol() // "symbol"
let arr = [1, 2, 3];
arr instanceof Array // true
let obj = { name: "John", age: 30 };
obj instanceof Object // true
Object.prototype.toString.call("hello"); // "[object String]"
Object.prototype.toString.call(42); // "[object Number]"
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(Symbol()); // "[object Symbol]"
Object.prototype.toString.call([]); // "[object Array]"
Object.prototype.toString.call({}); // "[object Object]"
```