js基础数据类型的纠葛以及类型判断

基本类型与引用类型

基本类型:number、string、boolean、undefined、null、
引用类型:object(包括array/function)

根据JS的语法,要满足===的条件如下:

  1. 如果是引用类型,则两个变量必须指向同一个对象(同一个地址);
  2. 如果是基本类型,则两个变量除了类型必须相同外,值还必须相等。

判断类型

一.判断数组

1、typeof
typeof Null = 'object';
typeof Undefined = 'undefined';
typeof Function = 'function';
typeof Array = 'object';
typeof Object = 'object';
2、instanceof

instanceof运算符可以用来判断某个构造函数的prototype属性所指向的對象是否存在于另外一个要检测对象的原型链上。

array instanceof Array = true;
array instanceof Object = true;
object instanceof Object = true;
object instanceof Array = false;
3、constructor

实例化的数组拥有一个constructor属性,这个属性指向生成这个数组的方法。虽然可以用constructor判断是不是数组,但是极其容易改写了constructor。

array.constructor = 'function Array(){ [native code] }';
object.constructor = 'function Object(){ [native code] }';
4、Object.toString()

使用Object.prototype.toString方法来判断,每一个继承自Object的对象都拥有toString的方法。如果一个对象的toString方法没有被改写过,那么toString方法会返回’[object type]’。
Object.toString()方法不能用,比如:

['hello'].toString = 'hello';
'hello'.toString = 'hello';
{"a": 'hello'}.toString = '[object Object]'

array/object/string等的prototype都是object,所以他们的prototype都有toString这个方法。

Object.prototype.toString.apply(array) == '[object Array]';
Object.prototype.toString.apply(object) == '[object Object]';
Object.prototype.toString.apply(string) == '[object String]';

apply和call都可以用来改变toString的执行上下文。
使用Object.prototype.toString来判断是否是数组的前提是不能重写toString方法。

5、isArray

isArray是ES6中的新方法,不管怎样改变toString或者constructor都可以正常使用。

Array.isArray(array) = true;

最终方法

if(!Array.isArray){
    Array.isArray = function(arg) {
        return Object.prototype.toString.call(arg) === '[object Array]';
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值