js类型判断
一、js中共有8种数据类型,分别为:
-
String:字符串。
-
Number:数字。
-
Boolean:布尔值。
-
Undefined:未定义,即声明变量但未给变量赋值。
-
Null:表示为空的对象。
-
Object:对象。
-
Function:函数,一种特殊的对象,其特殊性表现为该对象中储存的为代码,可以执行。
-
Array:数组,一种特殊的对象,其特殊性表现为该对象中储存的是有序的数据。
二、区分数据类型 (三种)
1. 使用 typeof
返回的字符串有 'String'、'Number'、'Boolean'、'Undefined'、'Function'、'Object'
缺点 无法判断 Null、Object、Array三种类型 使用typeof判断都返回 ‘Object’
console.log(typeof 1); // 输出: 'number'
console.log(typeof 'jack'); // 输出: 'string'
console.log(typeof true); // 输出: 'boolean'
console.log(typeof undefined); // 输出: 'undefined'
console.log(typeof new Function()); // 输出: 'function'
console.log(typeof [1, 2]); // 输出: 'object'
console.log(typeof {name: 'jack'}); // 输出: 'object'
console.log(typeof null); // 输出: 'object'
2. 使用 instanceof
语法:
object instanceof constructor // 返回值为true或false
-
object
:某个实例对象 -
constructor
:某个构造函数
可判断的类型:String、Number、Boolean、Object、Function、Array
缺点 不能判断断Undefined、Null
另外
const arr = [1, 2, 3];
const obj = { name: 'John', age: 25 };
console.log(arr instanceof Array); // 输出: true
console.log(obj instanceof Object); // 输出: true
console.log(arr instanceof Object); // 输出: true(数组也是对象的一种)
3. 使用 Object.prototype.toString
返回的字符串包含了更详细的信息
Object.prototype.toString.call(null) // 返回值 '[object Null]'
Object.prototype.toString.call(undefined) // 返回值 '[object Undefined]'
Object.prototype.toString.call(1) // 返回值 '[object Number]'
Object.prototype.toString.call(true) // 返回值 '[object Boolean]'
Object.prototype.toString.call({name: 'jack'})// 返回值 '[object Object]'
Object.prototype.toString.call([1, 2]) // 返回值 '[object Array]'
Object.prototype.toString.call('jack') // 返回值 '[object String]'
Object.prototype.toString.call(new Function()) // 返回值 '[object Function]'