zoukankan      html  css  js  c++  java
  • js 数组去重

    var arr = [1,2,8,9,5,8,4,0,4];
    /*
    模拟: 原始数组:[1,2,8,9,5,8,4,0,4]
    索引值:0,1,2,3,4,5,6,7,8
    伪新数组:[1,2,8,9,5,8,4,0,4]
    使用indexOf方法找到数组中的元素在元素在中第一次出现的索引值
    索引值:0,1,2,3,4,2,6,7,6
    返回前后索引值相同的元素:
    新数组:[1,2,8,9,5,4,0]
    */
    function unique( arr ){
    // 如果新数组的当前元素的索引值 == 该元素在原始数组中的第一个索引,则返回当前元素
    return arr.filter(function(item,index){
    return arr.indexOf(item,0) === index;
    });
    }
    console.log(unique(arr)); // 1, 2, 8, 9, 5, 4, 0

  • 相关阅读:
    6月16日
    9月15日
    9月14日
    9月13日
    9月12日
    6月11日
    梦断代码阅读笔记
    11周总结
    梦断代码阅读笔记
    10第一阶段意见评论
  • 原文地址:https://www.cnblogs.com/zkx4213/p/14372944.html
Copyright © 2011-2022 走看看