underscore.js 分析 第二天

Underscore源码中有这么句
obj.length === +obj.length
意思是typeof obj.length == number,即检测obj的长度是否是数字
我的理解:这么写是来检测一个对象数组的类型到底是数组还是对象。
在Javascript中变量分为基本类型和引用类型,基本类型是Undefined、Null、Boolean、Number和String。
其他的都是引用类型,引用类型就是对象。所以array本质也是对象。

var obj ={
   name : "zhangsan",
   age :23
}
var arr=[1,2,3];
console.log(obj.length);    //undefined
console.log(arr.length);    //3
console.log(typeof arr);    //object
console.log(arr instanceof Array); //true

注,之前的size方法有用到obj.length === +obj.length。

在1.9中,源码是

  // Return the number of elements in an object.
  _.size = function(obj) {
    if (obj == null) return 0;
    return isArrayLike(obj) ? obj.length : _.keys(obj).length;
  };

返回对象中元素的个数

如果是空对象返回0,如果是数组对象返回length。

 



posted @ 2013-10-27 19:47  飞凡123  阅读(189)  评论(0编辑  收藏  举报