• JS数组遍历的方法


    for

    最简单的一种循环遍历方法,也是使用频率最高的一种,可优化
        循环过程中支持修改索引(修改 i)

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

      

    for…in…

    这个循环用的人也很多,但是效率最低(输出的 key 是数组索引),

    如果遍历的是对象,输出的则是对象的属性名

    var arr = ['', '', '', '', '', '']
    for(let key in arr) {
        console.log(key)
    }
    
    // 0 1 2 3 4 5
    
    let obj = {
            a: 11,
            b: 22,
            c: 33
    }
    for(let key in obj) {
        console.log(key)
    }
    // a b c 

    for…of…(ES6)

    虽然性能要好于 for..in...,但仍然比不上普通的 for 循环
        注意:不能循环对象,因为任何数据结构只要部署 Iterator接口,就可以完成遍历操作,有些数据结构原生具备 Iterator 接口,比如Array、Map、Set、String等,而 Iterator 接口是部署在数据结构的Symbol.iterator属性上的,而对象Object恰恰是没有Symbol.iterator属性的,所以无法被for..of遍历

    var arr = ['我', '是', '谁', '我', '在', '哪']
    for(var key of arr) {
        console.log(key)
    }
    
    // 我 是 谁 我 在 哪
    

      

    forEach(也叫作增强for循环)

     1. 数组里的元素个数有几个,该方法里的回调就会执行几次
        2. 第一个参数是数组里的元素,第二个参数为数组里元素的索引,第三个参数则是它自己(利用第三个参数可以进行数组去重)
        3. 数组自带的遍历方法,foreach在循环次数未知或者计算起来较复杂的情况下效率比for循环高
        4. 循环的数组元素是基本数据类型,不会改变原数据的数据,循环的数组元素为对象,会改变原数组的对象属性的值
        5. 循环过程中不支持修改索引,回调中使用return不会报错,但是无效
        注意:不能使用break和continue跳出整个循环或当前循环的,会报错,但是结合try...catch可以实现跳出循环

    var arr = [1, 2, 3, 4, 5, 6]
    arr.forEach((item, idnex, array) => {
        console.log(item)     // 1 2 3 4 5 6
        console.log(array)    // [1, 2, 3, 4, 5, 6]
    })
    
    // 循环的数组元素是基本数据类型,不会改变原数据的数据
    var arr1 = [1, 2, 3, 4, 5, 6]
    arr1.forEach((item) => {
        item = 10
    })
    console.log(arr1) // [1, 2, 3, 4, 5, 6]
    
    // 循环的数组元素为对象,会改变原数组的对象属性的值
    var arr2 = [
        { a:1, b:2 },
        { a:11, b:12 }
    ]
    arr2.forEach((item) => {
        item.a = 10
    })
    console.log(arr2) //  [{a: 10, b: 2}, {a: 10, b: 2}]
    
    // 使用try...catch...可以跳出循环
    try {
       let arr = [1, 2, 3, 4];
       arr.forEach((item) => {
           // 跳出条件
           if (item === 3) {
               throw new Error("LoopTerminates");
           }
           console.log(item);
       });
    } catch (e) {
        if (e.message !== "LoopTerminates") throw e;
    };
    // 1 2
    

      

    map(ES6)

    遍历每一个元素并且返回对应的元素(可以返回处理后的元素) (map 映射 一一 对应)
        返回创建的新数组和原来旧数组的长度是一样的,使用比较广泛,但其性能还不如 forEach
        前两种写法都会改变原数组,第三中方式则不会改变原数组
        注意:不能使用break和continue跳出整个循环或当前循环的,会报错,但是结合try...catch可以实现跳出循环

    // 一、会改变原数组
    var arr = [1, 2, 3, 4, 5, 6]
    var newArr = arr.map(function (item, idnex) {
        return item * item
    })
    
    console.log(arr)      // [1, 2, 3, 4, 5, 6]
    console.log(newArr)   // [1, 4, 9, 16, 25, 36]
    
    // 二、会改变原数组元素中对象的属性值
    var arr = [{a: 1, b: 2},{a: 11, b: 12}]
    let newARR = arr.map((item)=>{
        item.b = 111
        return item
    })
    console.log('arr数组',arr) // [{a: 1, b: 111},{a: 11, b: 111}]
    console.log('newARR',newARR) // [{a: 1, b: 111},{a: 11, b: 111}]
    
    // 三、不会改变原数组
    var arr = [{a: 1, b: 2},{a: 11, b: 12}]
    let newARR = arr.map((item)=>{
        return {
        	...item,
        	b:111
        }
    })
    console.log('arr数组',arr) // [{a: 1, b: 2},{a: 11, b: 12}]
    console.log('newARR',newARR) // [{a: 1, b: 111},{a: 11, b: 111}]
    
    // 四、使用try...catch...可以跳出循环
    try {
        var arr = [1, 2, 3, 4];
        arr.map((item) => {
            //跳出条件
            if (item === 3) {
                throw new Error("LoopTerminates");
            }
            console.log(item);
            return item
        });
    } catch (e) {
        if (e.message !== "LoopTerminates") throw e;
    };
    // 1 2
    

      

    filter(ES6)

    遍历数组,过滤出符合条件的元素并返回一个新数组

    var arr = [
    	{ id: 1, name: '买笔', done: true },
    	{ id: 2, name: '买笔记本', done: true },
    	{ id: 3, name: '练字', done: false }
    ]
        
    var newArr = arr.filter(function (item, index) {
    	return item.done
    })
    
    console.log(newArr)
    
    // [{ id: 1, name: '买笔', done: true },{ id: 2, name: '买笔记本', done: true }]
    

      

    some(ES6)

    遍历数组,只要有一个以上的元素满足条件就返回 true,否则返回 false

    var arr = [
    	{ id: 1, name: '买笔', done: true },
    	{ id: 2, name: '买笔记本', done: true },
    	{ id: 3, name: '练字', done: false }
    ]
    
    var bool = arr.some(function (item, index) {
    	return item.done
    })
    
    console.log(bool)    // true
    

      

    every(ES6)

    遍历数组,每一个元素都满足条件 则返回 true,否则返回 false

    var arr = [
    	{ id: 1, name: '买笔', done: true },
    	{ id: 2, name: '买笔记本', done: true },
    	{ id: 3, name: '练字', done: false }
    ]
    
    var bool = arr.every(function (item, index) {
    	return item.done
    })
    
    console.log(bool)    // false
    

      

    find(ES6)

    遍历数组,返回符合条件的第一个元素,如果没有符合条件的元素则返回 undefined

    var arr = [1, 1, 2, 2, 3, 3, 4, 5, 6]
        
    var num = arr.find(function (item, index) {
    	return item === 3
    })
    
    console.log(num)   //  3
    

      

    findIndex(ES6)

     遍历数组,返回符合条件的第一个元素的索引,如果没有符合条件的元素则返回 -1

    var arr = [1, 1, 2, 2, 3, 3, 4, 5, 6]
        
    var num = arr.findIndex(function (item) {
    	return item === 3
    })
    
    console.log(num)   //  4
    

      

    ————————————————
    版权声明:本文为CSDN博主「半度℃温热」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/fu983531588/article/details/89597521

  • 相关阅读:
    【微信小程序】 自定义组件
    vue3中的组件通讯
    vue3如何使用watch监听
    windows server 2008中iis7中的php5.3出现 Server 内部错误500的解决
    在计算里面计算为什么要采用补码
    计算机里二进制与十进制互相转到到底是怎么完成的
    矩的概念、意义以及在SLAM中的应用
    VC++6.0 使用jsoncpp静态库解析json数据(亲测绝对可用)
    python等待用户输入并超时退出
    使用WTV工具箱检测有效电视源
  • 原文地址:https://www.cnblogs.com/llllpzyy/p/15210525.html
Copyright © 2020-2023  润新知