数组去重方法
使用最基本的两个数组嵌套循环遍历 :
….
使用数组的filter()方法 :
1 | array.filter(function(currentValue,index,arr), thisValue); |
1 | var arr = ['apple','strawberry','banana','pear','apple','orange','orange','strawberry']; |
利用数组的reduce()方法 :
reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
reduce() 对于空数组是不会执行回调函数的。
1 | array.reduce(function(previousValue, currentValue, currentIndex, arr){...}, initialValue) |
| 参数 | 描述 | 备注 |
|---|---|---|
| array | 应用该方法的对象数组 | 必需 |
| previousValue | 通过上一次调用回调函数获得的值。如果向 reduce 方法提供 initialValue,则在首次调用函数时,previousValue 为 initialValue。 | 必需 |
| currentValue | 当前数组元素的值 | 可选 |
| currentIndex | 当前数组元素的数字索引 | 可选 |
| arr | 包含该元素的数组对象 | 可选 |
完整代码:
1 | // 使用reduce数组去重 |
使用indexOf配合数组的splice() :
indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。该方法适用于数组
1 | stringObject.indexOf(searchvalue,fromindex) |
splice() 方法向/从数组中添加/删除项目,然后返回被删除的项目。该方法会改变原始数组
1 | arrayObject.splice(index,howmany,item1,.....,itemX) |
完整代码:
1 | //借助indexOf()方法判断此元素在该数组中首次出现的位置下标与循环的下标是否相等 |