js遍历数组和对象的方式

遍历数组或对象的常用方式有for、for-in、for-of、forEach和map

const arr = [1,2,3,4,5]
const obj = {
    id:1,
    name:'tom',
    age:18
}
const str = "abc"

1. for

使用for循环是最基本的遍历方式

遍历的是索引

for(let i = 0;i<arr.length;i++){
    console.log(arr[i]);  //1 2 3 4 5
}

for(let i = 0;i<str.length;i++){
    console.log(str[i]);  //a b c
}

 2. for-in

遍历数组和字符串遍历的是索引,遍历对象遍历的是键

for(let i in arr){
    //遍历索引
    console.log(arr[i]);  //1 2 3 4 5
}
for(let i in str){
    //遍历索引
    console.log(str[i]); //a b c
}
for(let i in obj){
    //遍历键
    console.log(i,obj[i]);
    //id 1
    //name tom
    //age 18
}

3. for-of

可以遍历可迭代对象,不可遍历对象

遍历的是值

for(let i of arr){
    console.log(i);  //1 2 3 4 5
}
for(let i of str){
    console.log(i);  //a b c 
}

4. forEach和map

两者用法差不多,都是遍历数组的方法

且都可以传递三个参数,第一个为当前项,第二个为索引,第三个为原数组。后两个参数可省略。

forEach

没有返回值,返回的结果为undefined。除了抛出异常以外,没有办法中止或跳出循环。

map

有返回值,每个元素都按顺序调用一次callback函数,返回一个新数组。

两个方法都不会修改原数组。

let arr = [2,5,8,4,9]
let res1 = arr.forEach(item=>item*2)
console.log(res1);  //undefined
console.log(arr);  //[ 2, 5, 8, 4, 9 ]

let res2 = arr.map(item=>item*2)
console.log(res2)  //[ 4, 10, 16, 8, 18 ]
console.log(arr);  //[ 2, 5, 8, 4, 9 ]

如果想要修改原数组的话,可以通过索引的方式进行修改。

let res3 = arr.forEach((item,index,input)=>{
    input[index] = item*2
})
console.log(arr);  //[ 4, 10, 16, 8, 18 ]

let res4 = arr.map((item,index,input)=>{
    input[index] = item*2
})
console.log(arr);  //[ 8, 20, 32, 16, 36 ]

  • 8
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值