循環遍歷數組或者對象,for、forEach、for in 、 for of 使用最多javascript
for (語句 1; 語句 2; 語句 3) {
要執行的代碼塊
}java
var arr = [1,2,3,4]
for(var i = 0 ; i< arr.length ; i++){
console.log(arr[i]); // 1 2 3 4 (輸出結果)
}es6
let arr = ['a', 'b', 'c', 'd']
arr.forEach(function (val, idx, arr) {
console.log(val + ', index = ' + idx) // val是當前元素,index當前元素索引,arr數組
console.log(arr)
})數組
a, index = 0es5
(4) ["a", "b", "c", "d"]
b, index = 1設計
(4) ["a", "b", "c", "d"]
c, index = 2對象
(4) ["a", "b", "c", "d"]
d, index = 3索引
(4) ["a", "b", "c", "d"]ip
let obj = {a: '1', b: '2', c: '3', d: '4'}
for (let o in obj) {
console.log(o) //遍歷的其實是對象的屬性名稱 a,b,c,d
console.log(obj[o]) //這個纔是屬性對應的值1,2,3,4
}字符串
let arr = ['China', 'America', 'Korea']
for (let o of arr) {
console.log(o) //China, America, Korea
}
let obj = {a: '1', b: '2', c: '3', d: '4'}
for (let o of obj) {
console.log(o) //Uncaught TypeError: obj[Symbol.iterator] is not a function
}
let obj = {a: '1', b: '2', c: '3', d: '4'}
for (let o of Object.keys(obj)) {
console.log(o) // a,b,c,d
}
let obj = {a: '1', b: '2', c: '3', d: '4'}
for (let o of Object.values(obj)) {
console.log(o) // 1,2,3,4
}
let str = 'love'
for (let o of str) {
console.log(o) // l,o,v,e
}
let iterable = new Map([["a", 1], ["b", 2], ["c", 3]]);
for (let [key, value] of iterable) {
console.log(value);
}
// 1
// 2
// 3
for (let entry of iterable) {
console.log(entry);
}
// [a, 1]
// [b, 2]
// [c, 3]
let iterable = new Set([1, 1, 2, 2, 3, 3]);
for (let value of iterable) {
console.log(value);
}
// 1
// 2
// 3
let iterable = new Uint8Array([0x00, 0xff]);
for (let value of iterable) { console.log(value); } // 0 // 255