1

一.js中的数据类型

js中的数据类型有7种:Number,String,Boolean,Null,undefined,Symbol,Object。

注: function Array 也是Object

3种常见的js数据类型分类

1.常见分类方式

原始类型: Number、String、Boolean、Null、undefined、Symbol
对象类型: Object

2.基本数据类型和引用数据类型。

JS基本数据类型(按值问):Number,String,Boolean,null,undefined,Symbol

引用数据类型(按引用访问):Object,Array,function

3.按值是否可变分类

不可变类型: Number,String,Boolean,Null,undefined,Symbol
可变类型:~~~~ Object,Array

js种数据类型判断

废话不多说先来总结:~~~~

/**总结:
 * 1.typeof能准确判断出基本数据类型,但是不能判断引用数据类型。判断引用类型时除function外其他判断结果都为object。
 * 2.instanceof 不能判断基本数据类型,但是能准确判断引用数据类型。这是因为instanceof是通过能否找到构造函数的原型对象来判断的。
 * 3.Object.prototype.toString.call()能准确判断任何数据类型
 */

具体示例如下:

let num=111;
let str='hello';
let flag=true;

/**引用数据类型 */
let arr=[1,2,3];
let obj={name:'zhangsan',age:18};
const func=function(){
    console.log('---function');
};
/**typeof判断数据类型 */
console.log(typeof num);//number
console.log(typeof str);//string
console.log(typeof flag);// boolean
console.log(typeof null);//object---null本身就是对象,常用来函数中返回不存在的对象。
console.log(typeof undefined);//undefined
console.log(typeof Symbol);//function

console.log(typeof arr);//object
console.log(typeof obj);//object
console.log(typeof func);//function

/**typeof 判断数据类型总结:typeof能很好的判断基本数据类型,但是对于引用数据类型不能很好判断。
 * 引用数据类型除function能判断外,其他判断结果都为object。
 */

/**instanceof判断引用数据类型 */
console.log(num instanceof Number);//false
console.log(str instanceof String);//false
console.log(flag instanceof Boolean);//false
console.log(Symbol instanceof Symbol);//false

console.log(arr instanceof Array);//true
console.log(obj instanceof Object);//true
console.log(func instanceof Function);//true

/**instanceof判断数据类型总结:instanceof不能判断基本数据类型,能判断引用数据类型 */

/**Object.prototype.toString.call()判断数据类型 */
console.log(Object.prototype.toString.call(num));//[object Number]
console.log(Object.prototype.toString.call(str));// [object String]
console.log(Object.prototype.toString.call(flag));// [object Boolean]
console.log(Object.prototype.toString.call(null));// [object Null]
console.log(Object.prototype.toString.call(undefined));// [object Undefined]
console.log(Object.prototype.toString.call(Symbol));// [object Function]

console.log(Object.prototype.toString.call(arr));//[object Array]
console.log(Object.prototype.toString.call(obj));// [object Object]
console.log(Object.prototype.toString.call(func));// [object Function]

符道胜
1 声望1 粉丝

Gitee地址:[链接]