ES6提供了很多新的语法特性,使得遍历常用数据结构变得更加容易。下面介绍一些ES6中遍历常用数据结构的技巧:
1. 遍历数组:
- for循环:可以使用for循环来遍历数组,例如:
let arr = [1,2,3,4,5]; for(let i = 0; i < arr.length; i++) { console.log(arr[i]); }
- forEach()方法:可以使用forEach()方法来遍历数组,例如:
let arr = [1,2,3,4,5]; arr.forEach(function(item,index) { console.log(item); });
- for...of循环:可以使用for...of循环来遍历数组,例如:
let arr = [1,2,3,4,5]; for(let item of arr) { console.log(item); }
2. 遍历对象:
- for...in循环:可以使用for...in循环来遍历对象,例如:
let obj = {a:1,b:2,c:3}; for(let key in obj) { console.log(key); }
- Object.keys():可以使用Object.keys()方法来遍历对象,例如:
let obj = {a:1,b:2,c:3}; let keys = Object.keys(obj); keys.forEach(function(key) { console.log(key); });
- Object.values():可以使用Object.values()方法来遍历对象,例如:
let obj = {a:1,b:2,c:3}; let values = Object.values(obj); values.forEach(function(value) { console.log(value); });
- Object.entries():可以使用Object.entries()方法来遍历对象,例如:
let obj = {a:1,b:2,c:3}; let entries = Object.entries(obj); entries.forEach(function(entry) { console.log(entry); });
3. 遍历Set:
- for...of循环:可以使用for...of循环来遍历Set,例如:
let set = new Set([1,2,3,4,5]); for(let item of set) { console.log(item); }
- forEach()方法:可以使用forEach()方法来遍历Set,例如:
let set = new Set([1,2,3,4,5]); set.forEach(function(item,index) { console.log(item); });
4. 遍历Map:
- for...of循环:可以使用for...of循环来遍历Map,例如:
let map = new Map([['a',1],['b',2],['c',3]]); for(let [key,value] of map) { console.log(key,value); }
- forEach()方法:可以使用forEach()方法来遍历Map,例如:
let map = new Map([['a',1],['b',2],['c',3]]); map.forEach(function(value,key) { console.log(key,value); });