前端js的数组的循环遍历 for / for of / for in / arr.forEach()

  • A+
所属分类:Web前端
摘要

数组的作用是使用单独的变量名来存储一系列的值。数组的功能强大很 ,其方法也很多…

数组的作用是使用单独的变量名来存储一系列的值。数组的功能强大很 ,其方法也很多...

数组的循环遍历 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
//在循环中 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