JavaScript中的几种常用的遍历方式

82 阅读1分钟

数组遍历

for

let arr = [1, 3, 6, 11, 23, 24, 30]
        for (let i = 0; i < arr.length; i++) {
            console.log(arr[i])
        }

for 是比较常见的遍历方式,特点是用一个临时变量将数组长度缓存起来,即便是长度较大的数组也适用

forEach

let arr = [1, 3, 6, 11, 23, 24, 30]
arr.forEach(function (value, index) {
            console.log(`第${index + 1}个值为:${value}`);
        })

forEach 可以调用数组中的每个元素并传给回调函数,除了一个必要的值即当前元素之外,还可以有其它参数,如索引值index。一般用于数组遍历,无返回值

filter

let arr = [1, 3, 6, 11, 23, 24, 30]
let newArr = arr.filter(function (value) {
            return value > 20
        })
        console.log(newArr)

filter 一般用于数组过滤,一旦判定数组中的元素满足条件,会将满足条件的元素返回新的数组

map

let arr = [1, 3, 6, 11, 23, 24, 30]
let newArr = arr.map(function (value) {
            return value * 2
        })
        console.log(newArr)

map 同样用于数组遍历,与forEach一样,也会返回一个新数组,区别在于 filter 一般用于原数组的过滤,map 一般用于原数组的数据处理

对象遍历

for in

let obj = {a: 1, b: 2, c: 3} 
for (let i in obj) { 
console.log('键名:', i)
console.log('键值:', obj[i]) 
}

for in 一般用于对象遍历,每次遍历都会对对象的属性执行一次操作

其它

while

let num = 0
while (num < 5){ 
console.log(num)
num ++
}

while 也可以用于循环遍历,特点是 while 的判定条件为布尔值,只要结果为 true 就继续执行

do while

let num = 5 
do 
{ 
console.log(num)
num--
}
while(num >= 0)
console.log(num)

do while 和 while 相似,区别在于 do while 会在遍历之前先执行一次,再判断是否满足条件