综合
首页 > 学术社区 > 文章 > 正文

Javascript Array (from javascript:the good parts)


分享到:
评论(0)|2017-03-20|发布:nasa |收藏

Confusion

A common error in JavaScript programs is to use an object when an array is required

or an array when an object is required. The rule is simple: when the property names

are small sequential integers, you should use an array. Otherwise, use an object.

 

how to distinguish between arrays and objects?

 JavaScript does not have a good mechanism for distinguishing between arrays and

objects. We can work around that deficiency by defining our own is_array function:

is_array=function(value){
    return value && (typeof value)==="object" && value.constructor=Array
}

 

 Unfortunately, it fails to identify arrays that were constructed in a different window

or frame. If we want to accurately detect those foreign arrays, we have to work a little

harder:

is_array=function(value){
    return Object.prototype.toString.apply(value)==="[Object Array]";
}

 

Because an array is also an object,so we can add methods directory to an individual array:

var data=[1,2,3];
data.total=function(){
    var result=0;
    for(var i=0;i<this.length;i++){
         result+=this[i];
   }
   return result;
}
data.total();//return 6;

 Since the string "total" is not an integer,so adding a total property to an array does not change its length.

 


用手机扫描以上二维码直接访问此文。

系统分类:网页设计 >> javascript

评论
请登录再发布评论,所有评论仅代表网友意见,本网站保持中立