JavaScript 类型判断 instanceof typeof Object.prototype.toString.call([])

类型

  1. 基本类型 number, string, bool, null, undefined, 访问的是值。
  2. 复杂类型 array, function, object, 访问的是值的引用
//基本类型 
var a = 5;
var b = a;
b = 6;
a; //5
b; //6

//复杂类型
var a = ['hehe', 'haha'];
var b = a;
b[0] = 'heihei';
a[0]; //'heihei'
b[0]; //'heihei'

类型判断

1 new String Vs “string”

var a = 'bilibili';
var b = new String('bilibili');
a + b; //'bilibilibilibili'

//方法1
a instanceof String; //false
b instanceof String; //true

a.substr == b.substr; //true 两个变量确实都是字符串

//方法2
typeof a; //"string"
typeof b; //"object"

//方法3 ==
a == b; //true
a === b; //false

//方法4 对象内部的[[Class]]值,该值不可变。推荐此方法
Object.prototype.toString.call(a); //"[object String]"
Object.prototype.toString.call(b); //"[object String]"

所以正如《JavaScript : The Good parts》《JavaScript : 精粹》所说的,应避免使用new。

2 Array Vs Object (怎么判断变量是否为array)

var a = ['dog', 'cat'];
var b = new Array(['dog', 'cat']);
a == b; //true
a === b; //false

//方法1
a instanceof Array; //true
b instanceof Array; //true

//方法2 注意!array 会被判断为"object",不能用此方法
typeof a; //"object"
typeof b; //"object"

//方法3 es5的标准,被IE9+支持
Array.isArray(a); //true
Array.isArray(b); //true

//方法4 对象内部的[[Class]]值,该值不可变。推荐此方法
Object.prototype.toString.call(a); //"[object Array]"
Object.prototype.toString.call(b); //"[object Array]"

小心避免使用 方法2 typeof去判断array,难以与object区分开来。应用方法4.

3 true Vs false

var a = 0;
var b = null;
var c; //undefined
var d = '';

//注意!null 会被判断为"object"
typeof a; //"number"
typeof b; //"object"
typeof c; //"undefined"
typeof d; //"string"

a == false; //true 注意!
a === false; //false
b == false; //false
c == false; //false
d == false; //true 注意!
d === false; //false

//if 语句内 都会判断为false
if(a) {console.log("true");} //不会执行console.log("true");
if(b) {console.log("true");} //不会执行console.log("true");
if(c) {console.log("true");} //不会执行console.log("true");
if(d) {console.log("true");} //不会执行console.log("true");

4 typeof 的坑

从 2和3中,就可以看出typeof 在array和null的坑

var a = ['dog', 'cat'];
var b = null;

typeof a; //"object"
typeof b; //"object"
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值