天津网站建设哪家好邢台建网站哪里有
天津网站建设哪家好,邢台建网站哪里有,沈阳网站建设哪家便宜,网络营销中自建网站在 JavaScript 中#xff0c;给字符串数组#xff08;或其他类型数组#xff09;去重有多种方法#xff0c;下面列举几种常用的方式#xff0c;并说明各自的特点。1. 利用 Set#xff08;最简洁、推荐#xff09;
Set 是 ES6 新增的数据结构#xff0c;它类似于数组constunique[...newSet(arr)];console.log(unique);// [apple, banana, orange]优点代码简洁效率高时间复杂度 O(n)。缺点无法保留原数组中的元素顺序吗——会保留第一次出现的顺序Set 遍历顺序就是插入顺序因此顺序是保持的。所以一般没有缺点。但注意Set 去重使用“SameValueZero”比较认为NaN与自身相等而不认为相等在字符串数组中基本无影响。2. 利用filterindexOf通过数组自身的filter方法配合indexOf检测当前元素第一次出现的位置是否等于当前索引。constarr[apple,banana,apple,orange,banana];constuniquearr.filter((item,index)arr.indexOf(item)index);console.log(unique);// [apple, banana, orange]优点兼容性非常好ES5 即可语义清晰。缺点indexOf会从头遍历数组整体时间复杂度 O(n²)在大型数组上性能较差。同时indexOf无法正确查找NaN但字符串数组通常无此问题。3. 利用reduce累加器通过reduce构建新数组判断当前元素是否已存在于累加器中。constarr[apple,banana,apple,orange,banana];constuniquearr.reduce((acc,cur){if(!acc.includes(cur)){acc.push(cur);}returnacc;},[]);console.log(unique);// [apple, banana, orange]优点逻辑直观可灵活扩展。缺点includes也是遍历时间复杂度 O(n²)同时includes能处理NaN但字符串场景无影响。4. 利用对象/Map 作为哈希表性能最优使用Map或普通对象记录已出现的元素一次遍历即可时间复杂度 O(n)。constarr[apple,banana,apple,orange,banana];constmapnewMap();constuniquearr.filter(item{if(map.has(item))returnfalse;map.set(item,true);returntrue;});console.log(unique);// [apple, banana, orange]用对象也可以但对象键会被转为字符串对于纯字符串数组没问题但若数组中包含数字或其他类型需注意类型转换。constobj{};constuniquearr.filter(itemobj.hasOwnProperty(item)?false:(obj[item]true));优点线性时间复杂度适合大数据量。缺点代码略复杂。5. 进阶保持首次出现顺序 去重上述所有方法中除了Set和filterindexOf默认保持顺序其余若稍加调整也能保持顺序。Set和Map本身也是按插入顺序迭代因此上述基于Set和Map的方案自然保持顺序。总结日常开发推荐使用[...new Set(arr)]代码最简洁性能也不错。需要兼容极旧环境如 IE可用filterindexOf。大数据量且对性能有极致要求用Map哈希表方式。注意以上方法不仅适用于字符串数组同样适用于数字、混合类型数组但去重逻辑是基于严格相等或Set的 SameValueZero。对于对象数组则需要根据对象的某个属性去重以上方法需配合map提取属性值再进行去重。