数组常用方法
- 遍历相关:map、filter、some、every、reduce、reduceRight、for循环、for in、for of;
for in 和 for of 的区别
- for in 遍历数组弊端:
- index索引为字符串型数字,不能直接进行几何运算
- 遍历顺序有可能不是按照实际数组的内部顺序
- 会遍历数组所有可枚举属性,包括原型
- 遍历对象
- 会遍历到原型:解决办法(用hasOwnProperty做判断)
- 总结:
- for..of使用遍历数组、字符串、map、set等拥有迭代器对象的集合
- for..of不能遍历对象,因为没有迭代器对象
- for..of可以通过break、continue、return进行控制
- 遍历对象可通过for..in,Object.keys
遍历器
- Iterator概念:是一种机制,他是一个接口,为各种不同数据结构提供统一的访问机制,任何数据结构只要部署Iterator接口,就可以完成遍历操作
和for...of循环组合
- 作用:
- 为各种数据结构,提供统一的,简便的访问接口;
- 使得数据结构的成员能够按某种次序排列
- es6创造了一种新的遍历命令for...of循环,Iterator接口主要供for...of消费
- 可通过给对象添加Symbol.iterator属性让其具有iterator功能
- 具备Iterator接口的数据结构:
- Array
- Map
- Set
- String
- TypedArray(处理二进制的数组结构)
- 函数的arguments对象
- NodeList对象
- 模拟next
function makeIterator(array){
var nextIndex = 0;
return {
next:function() {
return nextIndex <array.length ?
(value: array[nextIndex++], done: false) :
(value: undefined, done: true)
}
}
}
var it = makeInterator(['a','b']);
it.next() // { value: "a", done: false }
it.next() // { value: "b", done: false }
it.next() // { value: undefined, done: true
参考网址:es6.ruanyifeng.com/#docs/itera…
参考网址:
www.jianshu.com/p/c43f418d6…