详解JS中遍历语法的比较

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

详解JS中遍历语法的比较

牧云云   2020-05-15 我要评论

for循环

JavaScript 提供多种遍历语法。最原始的写法就是for循环。

let arr = [1,2,3,4,5];

for (var index = 0; index < arr.length; index++) {
 console.log(myArray[index]); // 1 2 3 4 5
} 

缺点:这种写法比较麻烦

forEach

数组提供内置的forEach方法

let arr = [1,2,3,4,5];

arr.forEach((element,index) => {
  console.log(element); // 1 2 3 4 5
});

缺点:这种写法的问题在于,无法中途跳出forEach循环,break命令或return命令都不能奏效。

 for...in

for…in 用于遍历对象所有的可枚举属性,功能类似于Object.keys()。 

let obj = {
  name: 'cloud',
  phone: '157xxxx2065'
}
 
for (let prop in obj) {
  console.log(prop); // name phone
}

可能有朋友会问,不可枚举的对象有哪些呢? 比如constructor,数组的length就属于不可枚举属性。

let arr = [10, 20, 30, 40, 50];
 
for (let prop in arr) {
  console.log(prop); // '0' '1' '2' '3' '4'
}

缺点:

  1. 数组的键名是数字,但是for...in循环是以字符串作为键名“0”、“1”、“2”等等。
  2. for...in循环主要是为遍历对象而设计的,不适用于遍历数组

 for...of

for…of是ES6新增的遍历方式,它提供了统一的遍历机制。所有实现了[Symbol.iterator]接口的对象都可以被遍历。for...of循环可以使用的范围包括数组、Set 和 Map 结构、某些类似数组的对象(比如arguments对象、DOM NodeList 对象)、Generator 对象,以及字符串

优点:

  1. 有着同for...in一样的简洁语法,但是没有for...in那些缺点
  2. 不同用于forEach方法,它可以与breakcontinuereturn配合使用
  3. 提供了遍历所有数据结构的统一操作接口

下面是一个使用break语句,跳出for...of循环的例子。

for (var n of fibonacci) {
 if (n > 1000)
  break;
 console.log(n);
}

上面的例子,会输出斐波纳契数列小于等于1000的项。如果当前项大于1000,就会使用break语句跳出for...of循环。

 for...of获取索引

  1. entries() 返回一个遍历器对象,用来遍历[键名, 键值]组成的数组。对于数组,键名就是索引值;对于 Set,键名与键值相同。Map 结构的 Iterator 接口,默认就是调用entries方法。
  2. keys() 返回一个遍历器对象,用来遍历所有的键名。
  3. values() 返回一个遍历器对象,用来遍历所有的键值。
 // demo
let arr = ['a', 'b', 'c'];
for (let pair of arr.entries()) {
 console.log(pair);
}
// [0, 'a']
// [1, 'b']
// [2, 'c']

类似数组的对象

类似数组的对象包括好几类。下面是for...of循环用于字符串、DOM NodeList 对象、arguments对象的例子。

// 字符串
let str = "hello";

for (let s of str) {
 console.log(s); // h e l l o
}

// DOM NodeList对象
let paras = document.querySelectorAll("p");

for (let p of paras) {
 p.classList.add("test");
}

// arguments对象
function printArgs() {
 for (let x of arguments) {
  console.log(x);
 }
}
printArgs('a', 'b');
// 'a'
// 'b'

并不是所有类似数组的对象都具有 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); // 'a' // 'b'
}

普通的对象

对于普通的对象,for...of结构不能直接使用,会报错,必须部署了 Iterator 接口后才能使用。

let es6 = {
 edition: 6,
 committee: "TC39",
 standard: "ECMA-262"
};

for (let e in es6) {
 console.log(e);
}
// edition
// committee
// standard

for (let e of es6) {
 console.log(e);
}
// TypeError: es6 is not iterable

解决方法是,使用Object.keys方法将对象的键名生成一个数组,然后遍历这个数组。

for (var key of Object.keys(someObject)) {
 console.log(key + ': ' + someObject[key]);
}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们