<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body><script> //封装函数,找出数组 arr 中重复出现过的元素. //示例: console.log(duplicates( [1, 2, 4, 4, 3, 3, 1, 5, 3] )); //返回结果: 1, 3, 4 function duplicates(arr) { arr.sort(function (n, m) { return n - m; }); var subArr = []; for (var i = 0; i < arr.length; i++) { if (arr[i] == arr[i + 1]) { subArr.push(arr[i]); } } subArr.sort(function (n, m) { return n - m; }); for (var i = 0; i < subArr.length; i++) { if (subArr[i] === subArr[i + 1]) { subArr.splice(i, 1); i--; } } return subArr; } console.log(duplicates([1, 2, 4, 4, 3, 3, 1, 5, 3]))</script></body></html>
原文地址:https://www.cnblogs.com/yxs1530/p/10242451.html
时间: 2024-10-09 00:57:52