zoukankan      html  css  js  c++  java
  • 常用技巧之JS判断数组中某元素出现次数

    先上代码:
    function arrCheck(arr){
      var newArr = [];
      for(var i=0;i<arr.length;i++){
        var temp=arr[i];
        var count=0;
        for(var j=0;j<arr.length;j++){
          if(arr[j]==temp){
            count++;
            arr[j]=-1;
          }
        }
        if(temp != -1){
          newArr.push(temp+":"+count)
        }
      }
      return newArr;
    }

    arrCheck([1,2,3,3,4]);

    重点有三个:
    1,通过嵌套for循环,把数组的每一项,跟整个数组中的所有项,比较一遍;
    2,通过if判断,如果有相等的项,count++,并把相等的项置为-1,这样可以判断等于-1的就是重复的,就不再加入新数组了;
    3,用if判断!=-1,决定是否加入新数组中,返回。

    console.log(arrCheck([1,2,3,3,4]));

  • 相关阅读:
    DataGird导出EXCEL的几个方法
    csv文件与DataTable互相导入处理
    LeetCode 345
    LeetCode 168
    LeetCode 344
    LeetCode 342
    LeetCode 343
    LeetCode 326
    LeetCode 338
    LeetCode 319
  • 原文地址:https://www.cnblogs.com/winyh/p/6849666.html
Copyright © 2011-2022 走看看