遍历数组的方法

for循环遍历数组

let arr = [10, 23, 45, 56, 89];
for(let i = 0; i < arr.length;i++){
  console.log(i,arr[i]);
}

image-20220403171348752

for-in循环

let arr = [10, 23, 45, 56, 89];
for(let i in arr){
    //i 是数组的下标 arr[i] 读取数组中的值
    console.log(i,arr[i]);
}

image-20220403171500996

forEach( )遍历数组

说明:forEach()遍历数组 数组对象的方法 参数是一个函数,函数有俩个参数

let arr = [10, 23, 45, 56, 89];
arr.forEach(function(item,index){
    // item 代表数组中的每个值,  index 代表数组的索引值
    console.log(item,index);
})

image-20220403171632761

map( ) 遍历数组

说明:返回值是一个新数组; 执行的操作是把原数组中的每个值按照指定的规则映射到新数组中

let newArr = arr.map(function(item,index){
    //  item 代表数组中的每个值,  index 代表数组的索引值
    console.log(item,index);
    // 指定映射规则,通过return返回映射后的值
    return item * 10;
})
console.log(newArr);

image-20220403172645042

posted @ 2022-04-03 17:30  秋弦  阅读(146)  评论(0编辑  收藏  举报