數組的作用是使用單獨的變量名來存儲一系列的值。數組的功能強大很 ,其方法也很多...
數組的循環遍歷 for / for of / for in / arr.forEach()
for 循環
最簡單的一種,也是最靈活的
let arr=[1,2,3];
for(let y=0;y<arr.lngth;y++){
console.log(arr[y])
}
for of
//在循環中 let 的 item 就是遍歷了的值 他可以更好的方便我們書寫代碼
let arr=[1,2,3];
for(let item of arr){
console.log(item)
}
for in 在某些情況下遍歷會出錯,他存在bug
//在循環中 let 的 index 為下標 ,和 for of 一樣,更簡潔的數組遍歷方法
for(let index in arr){
console.log(arr[index])
}
arr.forEach()
arr.forEach()//==
arr.forEach(callback)//==
arr.forEach(function(item,index){//item 是元素,index 從零開始,可以表示為數組的下標
console.log(item);//元素
console.log(index);//下標
})
//可以拿到數組的下標和元素
//沒返回值
//輸出數組內的數字相加的和
例子 for of / arr.forEach
let arr = [1, 4, 34, 23, 4, 8, 12, 7], sum = 0, sum1 = 0;
for (let item of arr) {
sum += item
}
console.log(sum);//93
arr.forEach(function (item) {
sum1 += item
})
console.log(sum1);//93