一、数据结构
在JavaScript中常见的数据结构分为原始类型(Boolean、String、undefined、null)和引用类型(Object)。引用类型里细分又可分为Array、Function、Date等。对象和数组Array的区别在于:对象使用命名索引(即key,key-value对中的key类型为string),而数组是特殊类型的对象其使用数字索引。如果希望元素名为字符串(文本),则应使用对象;如果希望元素名为数字,则应使用数组。
我们平时经常见到的类数组对象(伪数组)实质上属于对象,但并非Array。伪数组具备两个特征:(1)按索引方式储存数据;(2)具有length属性。但它只是在特性上像数组,而不具备数组从Array.prototype中继承的方法(尽管如此,可以间接地使用Function.call方法调用,如[].slice.call(arguments))。并且数组具有其他对象所没有的特性:1)当有新的元素添加到列表时,自动更新length属性;2)设置length为一个较小值将截断数组。
那如何识别数组呢?
(1)ES3方法:instanceof运算符;
(2)ES5方法:Array.isArray()
(3)自定义函数:利用constructor属性
var fruits = ['apple', 'banana', 'orange']
fruits instanceof Array // true
Array.isArray(fruits) // true
function isArrayIf(x) {
return x.constructor.toString().indexOf("Array") > -1
}
isArrayIf(fruits) // true
遍历方式总结:
![09cb47d0bd393e126a92add5c99cb836.png](https://i-blog.csdnimg.cn/blog_migrate/039da6141d4c2bfa18df788dd04bc3a0.jpeg)
二、遍历方式
2.1 for循环
处理数据类型为:数组和伪数组(因为这个方法要求有length属性及下标,只有Array和伪数组有)。
支持break、continue方式跳出循环;
![1e302502bef07364e55d5c5d8f64ce55.png](https://i-blog.csdnimg.cn/blog_migrate/6ae63f8d92efe32c16b40c1b87f7fcbe.png)
![29c5a0dc4d4e101d4571b5bf14558bd4.png](https://i-blog.csdnimg.cn/blog_migrate/36ea51e3dec23e22c039dd6556b20d74.png)