You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
var arr = [1,2,3,4,5,5,4,3,2,1,11]
function unique(arr) {
// 结果数组
var res = []
for (var i = 0, len = arr.length; i < len; i++) {
for (var j = 0, resLen = res.length; j < resLen; j++) {
if (res[j] === arr[i]) {
break;
}
}
// 如果arr[i]是唯一的,那么res的循环结束时,j 等于resLen
if (j === resLen) {
res.push(arr[i])
}
}
return res
}
两层循环的简化版,使用indexOf
const arr = [1,2,3,4,5,5,4,3,2,1,11]
function unique(arr) {
var res = []
for (var i = 0, len = arr.length; i < len; i++) {
if (res.indexOf(arr[i]) === -1) {
res.push(arr[i])
}
}
return res
}
Set去重
var arr = [1,2,3,4,5,5,4,3,2,1,11]
function unique(arr) {
return Array.from(new Set(arr))
}
4.filter去重
var arr = [1,2,3,4,5,5,4,3,2,1,11]
function unique(arr) {
return arr.filter((item, index) => {
return arr.indexOf(item) === index
})
}
1:两层循环,兼容性最好IE6-8都可以
4.filter去重
深拷贝
-- 目的就是要拷贝值而不是仅仅拷贝引用
1: JSON方法
2:循环递归
The text was updated successfully, but these errors were encountered: