企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
方法一(推荐):使用new set()方法 ``` function duplicates(arr) { // 过滤掉重复项后的原数据 let notRepeating = new Set(); // 存放重复出现过的数据 let Repeat = new Set(); // 遍历原数组 arr.forEach((item) => { if (notRepeating.has(item)) { // 若notRepeating中已经含有该元素,则存到Repeat中 Repeat.add(item); } else { notRepeating.add(item); } }); return Array.from(Repeat);//判断数组长度是否大于0即可知道是否重复 } ``` 方法二:使用`indexOf()`和`lastIndexOf()` ``` function duplicates(arr) { // 存放重复出现过的数据 let Repeat = []; arr.forEach((item) => { // 当元素第一次出现的位置与最后一次出现的位置不相等,代表该元素重复出现了 // 该元素重复出现了且Repeat数组中不含该元素,则向Repeat中添加该元素 if ( arr.indexOf(item) !== arr.lastIndexOf(item) && Repeat.indexOf(item) === -1 ) { Repeat.push(item); } }); return Repeat } ``` 方法三:双重for循环,前后对比 ``` //判断试验类型是否重复 if(this.detailPageData.length > 0){ for (let i = 0; i < this.detailPageData.length; i++) { for (let j = i + 1; j < this.detailPageData.length; j++) { if ( this.detailPageData[i].expType == this.detailPageData[j].expType ) { this.$message.error("试验列表中试验类型重复!"); return false; } } } } ``` 方法四:遍历获取需要判断的属性,获得新数组,通过new Set()方法的size属性和新数组length对比 ``` let arr = [{ "name": "张三", "id": 1 }, { "name": "李四", "id": 3 }, { "name": "张三", "id": 2 }, ]; let names = arr.map(item => item["name"]); let nameSet = new Set(names);//去重 if (nameSet.size == names.length) { console.log("没有重复值"); } else { console.log("有重复值"); } ```