---
title: "Javascript Array (from javascript:the good parts)"
author: "hedajia"
date: "2014-06-18T22:31:30Z"
tags: ["JavaScript"]
categories: ["编程语言"]
slug: "javascript-array-from-javascript-the-good-parts"
draft: false
lastmod: "2014-06-18T22:31:30Z"
id: 2082332
url: "https://hedajia.iteye.com/blog/2082332"
---

## 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.**