let obj={a:1,b:2};
for(let i of obj){console.log(i)}//报错let arr=[1,2,3];
for(let i of arr){console.log(i)}//1,2,3
es6位js增加了一款新的遍历方法for…of,但是由上可以看出,数组可以成功遍历,但是对象却报错,其报错信息是:‘obj[Symbol.iterator] is not a function’。object没有iterator接口,而iterator接口为for…of提供遍历条件,故报错。es6规定iterator接口部署在数据结构的Symbol.iterator属性,es6中,数组、set、map、类似数组等数据结构原生具备iterator接口。
●iterator:
typeof [][Symbol.iterator];//functiontypeof {}[Symbol.iterator];//undefinedtypeof''[Symbol.iterator];//functiontypeof document.querySelectorAll('div'[Symbol.iterator];//functiontypeofnew Set()[Symbol.iterator];//functiotypeofnew Map()[Symbol.iterator];//function/////object本身没有iterator接口,string也有提供iterator接口。for...of循环本质上是调用这个接口产生的便利器:let arr=[1,2,3,4];
let ite=arr[Symbol.iterator]();
for(let i of ite){console.log(i)};//1,2,3,4 iterator接口产生的对象进行遍历得到一样的遍历结果,我们也可以手动添加iterator接口
●for…of:
let arr=['a','b','c'];
arr.
for(let i in arr){console.log(i)};//0,1,2,遍历得到索引for(let i of arr){console.log(i)};//a,b,c遍历得到数组各项的值,在遍历数组时,二者的区别在于此letset=new Set([1,2,2,2,3,3,4]);
for(let i of set){consle.log(i)};//1,2,3,4