时间:2021-12-09 18:06:57 | 栏目:JavaScript代码 | 点击:次
1、方法一
var arr = [1, 2, 3, 1, 2, 4]; function arrayCnt(arr) { var newArr = []; for(var i = 0; i < arr.length; i++) { if(newArr.indexOf(arr[i]) == -1) { newArr.push(arr[i]) } } var newarr2 = new Array(newArr.length); for(var t = 0; t < newarr2.length; t++) { newarr2[t] = 0; } for(var p = 0; p < newArr.length; p++) { for(var j = 0; j < arr.length; j++) { if(newArr[p] == arr[j]) { newarr2[p]++; } } } for(var m = 0; m < newArr.length; m++) { console.log(newArr[m] + "重复的次数为:" + newarr2[m]); } } arrayCnt(arr);
2、方法二(set方法去重)
var arr = [1, 2, 3, 1, 2, 4]; function arrayCnt(arr) { var newArr = []; //使用set进行数组去重 newArr = [...new Set(arr)]; var newarr2 = new Array(newArr.length); for(var t = 0; t < newarr2.length; t++) { newarr2[t] = 0; } for(var p = 0; p < newArr.length; p++) { for(var j = 0; j < arr.length; j++) { if(newArr[p] == arr[j]) { newarr2[p]++; } } } for(var m = 0; m < newArr.length; m++) { console.log(newArr[m] + "重复的次数为:" + newarr2[m]); } } arrayCnt(arr);