eg1:遍歷數組javascript
var arr=['a','b','c','d']; for(let index in arr){ console.log(index);// 0 1 2 3 console.log(arr[index]);// a b c d }
eg2:遍歷對象java
var obj={ name:"Jin", age:11, [Symbol()]:123, } for(let index in obj){ console.log(index);//name age console.log(obj[index]);//Jin 11 }
eg3:遍歷對象的順序數組
var obj={ "49":"A", "a":"tt", "5":false, "1":"ss", } for(let index in obj){ console.log(index);//1 5 49 a console.log(obj[index])//ss false A tt }
eg1:遍歷數組瀏覽器
var arr=['a','b','c','d']; for(let key of arr){ console.log(key);// a b c d console.log(arr[key]); //undefined undefined undefined undefined }
eg2:遍歷對象數據結構
var obj={ "49":"A", "a":"tt", "5":false, "1":"ss", } for(let key of obj){//報錯 console.log(index); }
eg3:for of與Object.keys()遍歷對象函數
var obj={ name:"Jin", age:11, } for(let value of Object.keys(obj)){ console.log(value);//name age console.log(obj[value]);//Jin 11 }
eg4:for of與Object.keys()遍歷數組索引prototype
var arr=['a','b','c']; for(let value of Object.keys(arr)){ console.log(value);//0 1 2 console.log(arr[value]);// a b c }
eg4:for of與Object.entries()遍歷索引和值指針
var arr=['a','b','c']; for(let [index,value] of Object.entries(arr)){ console.log(index);//0 1 2 console.log(value);//a b c console.log(arr[index]);//a b c }
eg5:for of與Object.values()遍歷屬性值code
var arr=['a','b','c']; for(let [index,value] of Object.values(arr)){ console.log(index);//a b c console.log(value);//undefined undefined undefined console.log(arr[index]);//undefined undefined undefined }
for...of的要點:對象
一是爲各類數據結構,提供訪問接口;二是使得數據結構的成員可以按某種次序排列;三是 ES6 創造了一種新的遍歷命令for...of循環,當使用for...of循環遍歷某種數據結構時,該循環會自動去尋找 Iterator 接口。