ES5数组实例方法【forEach】

真的了解forEach?

forEach

  • forEach((value, index, arr) => {})
  • 作用:遍历数组,增强版/简化版的for循环
  • 返回:无返回值
  • 语法:
    array.forEach((value, index, arr) => {
    value: 数组中的每项元素
    index:数组中元素的下标值
    array:数组本身
    })
  • 查看数组的实例方法: Array.prototype
  • 不会改变原数组!不会改变原数组!不会改变原数组!

遍历简单数组

const beauty = ['小红', '小黄', '小蓝', '小绿']

beauty.forEach((value, index, arr) => {
    console.log('元素:' + value, '下标:' + index, '本身:' + arr)
    // 元素:小红 下标:0 本身:小红,小黄,小蓝,小绿
    // 元素:小黄 下标:1 本身:小红,小黄,小蓝,小绿
    // 元素:小蓝 下标:2 本身:小红,小黄,小蓝,小绿
    // 元素:小绿 下标:3 本身:小红,小黄,小蓝,小绿
})

遍历对象

const boys = [
    {
        name: '杜兰特',
        height: 200
    },
    {
        name: '库里',
        height: 192
    },
    {
        name: '巴特勒',
        height: 205
    },
    {
        name: '科比',
        height: 233
    }
]
boys.forEach((value, index) => {
    console.log('元素:' + value.name, '下标:' + index)
})
// 元素:杜兰特 下标:0
// 元素:库里 下标:1
// 元素:巴特勒 下标:2
// 元素:科比 下标:3

手写个forEach

Array.prototype._forEach = function (callback) {
    for (let i = 0; i < this.length; i++) {
        callback(this[i], i, this)
    }
}

const boys = [
    {
        name: '杜兰特',
        height: 200
    },
    {
        name: '库里',
        height: 192
    },
    {
        name: '巴特勒',
        height: 205
    },
    {
        name: '科比',
        height: 233
    }
]

boys._forEach((value, index) => {
    // this就是调用_forEach的数组对象,拿到之后,内部for循环实现
    console.log('元素:' + value.name, '下标:' + index)
})

// 元素:杜兰特 下标:0
// 元素:库里 下标:1
// 元素:巴特勒 下标:2
// 元素:科比 下标:3

水平有限,还不能写到尽善尽美,希望大家多多交流,跟春野一同进步!!!


版权声明:本文为jinchunye原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。