• 数组的一些常用操作


    以下只是数组的部分较常用功能

    一、数组去重

      (1)ES5方法! 利用 filter 和 indexOF方法

    
    
    let arr = [1, 1, 2, 3, undefined, null, null, 23, 'g', 'g']
    function uniq (array){
     return [].filter.call(array, function (item, index) { 
        return array.indexOf(item) == index 
        })
    }

    console.log(uniq(arr)) // [1, 2, 3, undefined, null, 23, "g"]

      

      (2)ES6方法! 利用 new Set()方法配合ES6 展开运算符: Set 对象允许你存储任何类型的唯一值,无论是原始值或者是对象引用

    let arr = [1, 1, 2, 3, undefined, null, null, 23, 'g', 'g']
    console.log([...new Set(arr)]) // [1, 2, 3, undefined, null, 23, "g"]

      (3)ES6方法! 利用 reduce

       

    (1)对普通数组去重
    let arr = arr = [1, 2 , 2, ,3, 2 ,4 ,1, 1, 1, 2]
    
    let newArr = arr.reduce(function (item, next) {
        obj[next] ? '' : obj[next] = true && item.push(next)
        return item
    }, [])
    console.log(newArr) // [1, 2, 3, 4]
    2)数组对象去重
    
    let arr2 = [
        {id: 1},
        {id: 1},
        {id: 1},
        {id: 2},
        {id: 4},
    ]
    let newArr2 = arr.reduce(function (item, next) {
        console.log(item)
        obj[next.id] ? '' : obj[next.id] = true && item.push(next)
        return item
    }, [])
    console.log(newArr2)

    二、数组某项第一个查找

      find() 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined

    const array1 = [5, 12, 8, 130, 44];
    
    const found = array1.find(item => item > 10);
    
    console.log(found); // 12

    三、数组遍历,可中断和不可中断 循环

      除了简单的 for , do...while 循环外,还有 forEach,map

       for 可以用 break 跳出循环遍历外,forEach,map 不能跳出遍历,

    let arr = [1, 1, 2, 3, undefined, null, null, 23, "g", "g"]
    
    for (let i = 0, len = arr.length; i < arr.len; i++) {
        console.log(i) // 0, 1, 2, 3
        if (i === 3) {
            break // 注意仅可用 break退出循环
        }
    }

     

  • 相关阅读:
    搭建Jfroum过程记录
    性能测试见解1
    线程与进程
    性能测试见解3需求分析
    软件功能测试的用例设计总结
    hadoop 2.x安装:不能加载本地库 解决libc.so.6 version GLIBC_2.14 not found问题
    hadoop 2.x安装:不能加载本地库 java.library.path错误
    linux使用:CentOS安装jdk
    hadoop 2.x安装:完全分布式安装
    hadoop 2.x安装:不能加载本地库 重新编译hadoop本地库
  • 原文地址:https://www.cnblogs.com/chase-star/p/12517505.html
Copyright © 2020-2023  润新知