JavaScript 学习-4.Array数组遍历的几种方式

前言

Array 数组遍历的几种方式

普通for循环

循环遍历基础语法

 for(var i = 0; i < arr.length; i++){
  ...
}

使用示例

var arr1 = ['hello', 'world', 'aa'];
for (var i=0; i<arr1.length; i++){
    console.log(i)      // 下标
    console.log(arr1[i])  // 成员
}

运行结果

for...in

for...in 循环的是数组下标,语法结构

 for(var index in arr){
  ...
}

示例

var arr1 = ['hello', 'world', 'aa'];
for (var index in arr1){
    console.log(index);   // 下标
    console.log(arr1[index])
}

运行结果

for...of

for...of循环的是数组成员,语法结构

for(var item of arr){
    ...
}

使用示例

var arr1 = ['hello', 'world', 'aa'];
for(var item of arr1){
    console.log(item)     // 成员
}

forEach

forEach 只有数组对象才有此方法, forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数。
注意: forEach() 对于空数组是不会执行回调函数的。

array.forEach(function(currentValue, index, arr), thisValue)

forEach() 中可以传2个参数,其中function(currentValue, index, arr)是必需。 数组中每个元素需要调用的函数。

function 参数 说明
currentValue 必需。当前元素
index 可选。当前元素的索引值。
arr 可选。当前元素所属的数组对象。

基础语法结果

var arr1 = ['hello', 'world', 'aa'];
arrObj.forEach(function(item, index, obj){
    // item 遍历出的每一个元素
    // index 元素对应的下标 
    // obj 数组本身
})

使用示例

var arr1 = ['hello', 'world', 'aa'];
arr1.forEach(function(item, index, obj){
    console.log(item) // item 遍历出的每一个元素
    console.log(index)  // index 元素对应的下标
    console.log(obj)  // obj 数组本身
    console.log(obj.length)  // obj 数组本身
})

其中thisValue是可选。它表示传递给函数的值一般用 "this" 值。当没有thisValue 参数时,在函数内部this指的是window对象

var arr1 = ['hello', 'world', 'aa'];

person = {
    name: 'yoyo',
    age: 22,
    words: function () {
          arr1.forEach(function (item) {
              console.log(this)    // window
           })
    }
}
person.words();

此时this指的是window对象

forEach传第二个参数thisValue是时, this才会指向外面的person对象

var arr1 = ['hello', 'world', 'aa'];

person = {
    name: 'yoyo',
    age: 22,
    words: function () {
          arr1.forEach(function (item) {
              console.log(this)    // window
           })
    },
    info: function () {
          arr1.forEach(function (item) {
              console.log(this)    // person
           }, this)
    }
}
person.words();
person.info();

遍历数组有很多方法,以上四种最常用,其中forEach是只有数组中才有的方法。

posted @   上海-悠悠  阅读(375)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2021-05-14 面试题-python3 个包含n个整数的数组nums,判断nums中是否存在三个元素,a,b,c,使得a+b+c=0
2020-05-14 Cypress web自动化17-fixture加载json文件数据
2018-05-14 appium+python自动化46-安装app三种方式
2017-05-14 python接口自动化4-绕过验证码登录(cookie)
点击右上角即可分享
微信分享提示