forked from shiiiiiiji/IFEEES
-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
- Set 方法
let arrList = [1,3,5,7,9,1,3,5]
Array.from(new Set(arrList)) // [1,3,5,7,9]
- 双重for循环 方法
思路:
- 新建一个为空的结果数组
- 外层 for 遍历原数组,内层循环遍历返回数组
- 判断内层循环数组当前元素和外层数组元素的值是否相等,是?退出内层循环
- 经过第二部后,此时内层循环数组的索引值和返回数组的长度正好相等,外层数组元素也是唯一的。
function unique1(arr){
//let arrList = [1,3,5,7,9,1,3,5]
for(let i=0;i<arr.length;i++){
for(let j=0;j<arr2.length;j++){
//如果返回数组和操作数组的值相等,结束循环,此时的j值刚好和返回数组的长度相等
if(arr2[j] === arr[i]) break
}
}
//返回数组和j值相等,则插入该值
if(arr2.length === j){
arr2.push(arr[i])
}
return arr2
}
// [1, 3, 5, 7, 9]
- indexOf 方法
思路:
- 创建一个新数组
- for循环原数组
- 判断结果数组是否存在当前元素,indexOf进行校验,不存在push进新数组
let arrOne = [1,3,5,7,9,1,3,5]
let arrTwo = []
for(let i=0;i<arrOne.length;i++){
if(arrTwo.indexOf(arrOne[i],0) === -1){
// indexOf 搜索 Array 对象的指定元素并返回该元素的索引,
arrTwo.push(arrOne[i])
}
}
// [1, 3, 5, 7, 9]
- filter 方法
思路:
- filter会返回一个新数组
- 返回满足:当前元素在原数组中的第一个索引等于当前索引值,则返回当前元素
let arr = [1,3,5,7,9,1,3,5]
arr.filter(function(currentValue,index,array){
return arr.indexOf(currentValue,0) === index
})
// [1, 3, 5, 7, 9]
- es6 数组扩展运算符 方法
let arr = [1,3,5,7,9,1,3,5]
arr = [...new Set(arr)]
// [1,3,5,7,9]
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels