用JS编写一个函数,返回数组中重复出现过的元素,见下面的代码:
var arr = [1, 2, 3, 1, 2, 3, 4, 5]; var getRepeat = function (arr) { var obj = {}; for (var i = 0, len = arr.length; i < len; i++) { if (obj[arr[i]] == undefined) { obj[arr[i]] = 1; } else { obj[arr[i]]++; } } for (var key in obj) { obj[key] <= 1 && delete obj[key]; } return Object.keys(obj); } console.log(getRepeat(arr));//打印结果:(3) ["1", "2", "3"]
而数组去重的方法详见我的另一篇博文-->数组去重
时间: 2024-10-21 05:59:54