JS面试题--数据类型及其判断

76 阅读1分钟

一、js的数据类型及判断

数据类型

基本数据类型:StringNumberBooleanUndefinedNullSymbol
引用数据类型:ObjectArrayFunction

判断数据类型的方法

  1. type of 检测基本数据类型

    语法:type of 后面加括号或者不加括号 特例:正则、{}、[]、null输出都为object

	console.log(typeof {});//object
	console.log(typeof []);//object
	console.log(typeof (null));//object
	console.log(typeof 123);//number
	console.log(typeof true);//boolean
	console.log(typeof function () {});//function
	console.log(typeof (undefined));//undefined
  1. instanceof 检测当前实例是否属于某个各类

    双目运算符 a instanceof b, 判断a的构造器是否为b,通过返回的布尔值进行判断引用类型的数据

	let a = new b;
	console.log(a instanceof b);//true
	console.log(b instanceof Object);//true
	let arr = [1,2,3,4];
	console.log(arr instanceof Array);//true
  1. constructor构造函数

    语法:实例constructor 对象的原型链有一个属性叫constructor

  2. hasOwnproperty 检测当前属性是否为对象的私有属性

    语法:obj.hasOwnporperty("属性名")

  3. is Array 判断是否为数组

    Array.isArray() 数组的原生方法isArray判断是否为数组

	console.log(Array.isArray([]));//true
	console.log(Array.isArray(new Array()));//true
  1. Object.portotype.toString

    语法:Object.prototype.toString.call([value]) 获取Object.portotype上的toString方法,让方法的this变为需要检测的数据类型值,并且让这个方法执行在Number、String、Boolean、Array、Function、RegExp… 这些类的原型上都有一个toString方法:这个方法就是把本身的值转化为字符串 总结 Object.prototype.toString执行的时候返回当前方法中的this的所属类信息,也就是,我想知道谁的所属类信息,我们就把这个toString方法执行,并且让this变为我们检测的这个数据值,那么方法返回的结果就是当前检测这个值得所属类信息

   Object.prototype.toString.call(12)     //[boject Number]
   Object.prototype.toString.call(true)   //[boject Boolean]
			//"[object Number]"
			//"[object String]"
			//"[object Object]"
			//"[object Function]"
			//"[object Undefined]"
			//"[object Null]"
			//"[object RegExp]"
			//"[object Boolean]"