提到遍历,就一定要知道symbol.Iterator,任何数据结构只要部署 Iterator 接口,就可以完成遍历操作。
- for是JavaScript中为我们提供的一个最原始的方法
/** 这种写法用起来没问题,就是不简洁。 **/
for (var index = 0; index < Array.length; index++) {
console.log(Array[index]);
}
- forEach数组提供的内置方法
这个看起来很简洁,缺点在于中途不能跳出循环,无法执行break,continue,return命令。
- for...in循环读取键名(更适合遍历对象)
/** 1、数组的键名是数字,而for...in则是以字符串“0”,“1”,“2”作为键名,所以不适合数组。 **/
let es6 = {
edition: 6,
committee: "TC39",
standard: "ECMA-262"
};
for (var index in es6) {
console.log(es6[index]);
}
/*** for..in循环不仅遍历数字键名,还会遍历手动添加其他键,甚至包括原型链上的键。 */
let arr = [3, 5, 7];
arr.foo = 'hello';
for (let i in arr) {
console.log(i); // "0", "1", "2", "foo"
}
- for...of循环读取键值(es6新提供的遍历命令,更适合数组)
/** 不但和foreach一样有着简洁的语法,而且可以配合return,break,continue命令。 */
for (var n of fibonacci) {
if (n > 1000)
break;
console.log(n);
}
/** 并不是所有类似数组的对象都具有 Iterator 接口,一个简便的解决方法,就是使用Array.from方法将其转为数组。 */
let arrayLike = { length: 2, 0: 'a', 1: 'b' };
// 报错
for (let x of arrayLike) {
console.log(x);
}
// 正确
for (let x of Array.from(arrayLike)) {
console.log(x);
}
最后
以上就是文静飞机最近收集整理的关于关于Iterator(遍历器)的干货的全部内容,更多相关关于Iterator(遍历器)内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复