关于javascript:JS判断基本类型

1次阅读

共计 999 个字符,预计需要花费 3 分钟才能阅读完成。

面试:根底 + 我的项目 + 算法 + 思考

根底

1. 判断数据类型

数据类型有
值类型(根本类型):字符串(String)、数字(Number)、布尔(Boolean)、对空(Null)、未定义(Undefined)、Symbol。

援用数据类型:对象(Object)、数组(Array)、函数(Function)。

javascript 判断数据类型的几种办法:
一、typeof 间接返回数据类型字段,然而无奈判断数组、null、对象,其中 null, [], {}都返回 “object”
typeof 1 //"number"
二、instanceof 判断某个实例是不是属于原型

// 构造函数
function Fruit(name, color) {
    this.name = name;
    this.color = color;
}
var apple = new Fruit("apple", "red");

// (apple != null)
apple instanceof Object  // true
apple instanceof Array   // false

三、应用 Object.prototype.toString.call()判断,call()办法能够扭转 this 的指向,那么把 Object.prototype.toString()办法指向不同的数据类型下面,返回不同的后果

Object.prototype.toString.call(1)
"[object Number]"

四、constructor 判断实例对象的构造函数,对根本数据类型没法用,因为在应用 constructor 的时候主动调用了 String()/Number()/Function() 构造函数生成一个对象

'a'.constructor === String  //true
(1).constructor === Number  //true
(function(){}).constructor === Function  //true
apple.constructor === Fruit  //ture

五、自写

function _typeof(obj){var s = Object.prototype.toString.call(obj);
  return s.match(/\[object (.*?)\]/)[1].toLowerCase();};


_typeof([12,3,343]);
"array"

参考:javascript 判断数据类型的几种办法

正文完
 0