zoukankan      html  css  js  c++  java
  • JavaScript数组扁平化、数组去重常见方法

    数组扁平化

    1.使用arr.flat()

    const arr = [1,[2,[3,[4,5]]], 6]
    const res = arr.flat(Infinity)
    

    2.使用正则

    const arr = [1,[2,[3,[4,5]]], 6]
    const res = JSON.stringify(arr).split(',').map(n=>Number.parseInt(n))
    

    3.正则版本2

    const arr = [1,[2,[3,[4,5]]], 6]
    const res = JSON.parse('[' + JSON.stringify(arr).replace(/[|]/g, '') + ']')
    

    数组去重

    1.使用Set

    const arr = [1, 1, '1', 17, true, true, false, false, 'true', 'a', {}, {}]
    const res = Array.from(new Set(arr))
    

    2.使用indexOf

    const arr = [1, 1, '1', 17, true, true, false, false, 'true', 'a', {}, {}]
    const res = []
    for(let i=0; i< arr.length; i++){
      if(res.indexOf(arr[i]) === -1) res.push(arr[i])
    }
    

    2.使用includes

    const arr = [1, 1, '1', 17, true, true, false, false, 'true', 'a', {}, {}]
    const res = []
    for(let i=0; i< arr.length; i++){
      if(!res.includes(arr[i])) res.push(arr[i])
    }
    

    3.使用filter

    const arr = const arr = [1, 1, '1', 17, true, true, false, false, 'true', 'a', {}, {}]
    const res = arr.filter((item, index)=> arr.indexOf(item)===index)
    

  • 相关阅读:
    常见错误集锦
    auto 迭代器的使用
    案例:带有动画的返回顶部
    案例:toDoList
    jQuery事件
    案例:发布微博功能
    案例:购物车功能模块
    jQuery常用的API
    案例:王者荣耀手风琴效果
    案例:jQuery实现tab栏切换功能
  • 原文地址:https://www.cnblogs.com/pangqianjin/p/14871376.html
Copyright © 2011-2022 走看看