zoukankan      html  css  js  c++  java
  • 数组的一些常用操作

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

    一、数组去重

      (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退出循环
        }
    }

     

  • 相关阅读:
    服务器组件
    SQLAlchemy
    SessionMiddleware源码分析
    java实现ftp文件上传下载,解决慢,中文乱码,多个文件下载等问题
    linux 实现自动创建ftp用户并创建文件夹
    window server 2008 配置ftp并实现用户隔离
    centos 6.5配置ftp服务器,亲测可用
    learnyounode 题解
    [写出来才有价值系列:node.js]node.js 02-,learnyounode
    Linux多台机器配置ssh免登录
  • 原文地址:https://www.cnblogs.com/chase-star/p/12517505.html
Copyright © 2011-2022 走看看