javascript中数据类型判断的几种方法

2021/12/23 14:07:18

本文主要是介绍javascript中数据类型判断的几种方法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

//检测数据类型的几种方法
//typeof
//typeof在对值类型number string boolean symbol function undefined反应是精准的
//typeof在对引用类型object array 和 null 都会返回object
console.log(typeof 1); //number
console.log(typeof '1');//string
console.log(typeof true);//boolean
console.log(typeof Symbol('symbol'));//symbol
console.log(typeof function () { });//function
console.log(typeof undefined);//undefined
console.log(typeof { 'title': 'title' });//object
console.log(typeof [1, 2, 3, 4, 5]);//object
console.log(typeof null);//object

//instanceof
//为弥补tpyeof对object类型判断的不准确性,instanceOf基于原型的角度对object判断是谁的实例
//用instanceOf判断一个实例是否属于某种类型
//instanceOf 只能判断对象类型的数据,基础数据类型不行
console.log([] instanceof Array);
console.log({} instanceof Object);

//undefined 和 null 会报错
console.log(null instanceof Object)//false

//用new生成的基础类型是引用类型而非值类型 因为用new时,new会申请内存,隐式的执行new object创建对象

//constructor
//所有的prototype 和实例化对象都有 constructor
console.log(("1").constructor === String); // true
console.log((1).constructor === Number); // true
console.log((NaN).constructor === Number); // true
console.log((true).constructor === Boolean); // true
console.log(([]).constructor === Array); // true
console.log((function () { }).constructor === Function); // true
console.log(({}).constructor === Object); // true
console.log((Symbol(1)).constructor === Symbol); // true

//console.log((null).constructor === Null); // 报错
//console.log((undefined).constructor === Undefined); // 报错
//当创建一个对象,并修改对象的原型,用constructor也就不准确了

//Object.prototype.toString.call()
//完美精准的返回各种数据类型
function checkedType(target) {
    return Object.prototype.toString.call(target).slice(8, -1)
}
console.log(checkedType(1)); // Number
console.log(checkedType("1")); // String
console.log(checkedType(NaN)); // Number
console.log(checkedType(true)); // Boolean
console.log(checkedType(Symbol(1))); // Symbol
console.log(checkedType(null)); // Null
console.log(checkedType(undefined)); // Undefined
console.log(checkedType([])); // Array
console.log(checkedType({})); // Object
console.log(checkedType(function () { })); // Function



//判断是不是数组
console.log(Array.isArray([])) //true
console.log(Array.isArray({})) //false


这篇关于javascript中数据类型判断的几种方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程