判断是否为数组
//判断是否为数组
let arr = [1,2]
//es6
console.log(Array.isArray(arr)) //true
console.log(typeof arr === Array) //false
console.log(arr instanceof Array) //true
console.log(arr.constructor === Array) //true
//推荐
console.log(Object.prototype.toString.call(arr) === '[object Array]') //true
console.log(arr.__proto__ === Array.prototype)
let fn = function(){}
console.log(fn.constructor === Function) //true
数组去重
let arr2 = [1,3,2,2,1,4,5,6,2,4,1,9,8]
//console.log('++'+arr2.indexOf(1))
//数组去重 method1
let myset = new Set(arr2)
console.log(myset)
console.log(myset.has(2))
myset.add(99)
//set的遍历
for(let i of myset) {
console.log(i)
}
//直接使用,返回数组推荐
let arr2_filter = [...new Set(arr2)]
console.log(arr2_filter)
//同样可以用来,去除重复字符串中的字符
console.log([...new Set('abcadcfpk')].join(''))
//也可以使用Arrary.from 返回数组 dedupe()
console.log(Array.from(new Set(arr2)))
//去重method2 includes
function debupe(arr2){
let res = []
for(let i = 0; i < arr2.length; i++) {
if(!res.includes(arr2[i])) {
res.push(arr2[i])
}
}
return res
}
console.log('原始方法')
console.log(debupe(arr2))
function debupe1(arr) {
return arr.filter((item, index, arr) => {
return arr.indexOf(item) === index
})
}
console.log('filter-indexOf')
console.log(debupe1(arr2))
//去重 method3 filter
function debupe2(arr) {
let myset = new Set()
return arr.filter(res => !myset.has(res)&&myset.add(res))
//return [...myset]
}
console.log('filter')
console.log(debupe2(arr2))
function debupe3(arr) {
let mymap = new Map()
//return arr.filter(res => !mymap.has(res)&&mymap.set(res,1))
arr.filter(res => !mymap.has(res)&&mymap.set(res,1))
return mymap.keys()
}
console.log('filter2')
console.log(debupe3(arr2))
// method3:reduce传统方法
let oldArr = [12,1,2,3,4,4,1,2,3]
let res11 = oldArr.reduce((cur, next) => {
if(!cur.includes(next)){
cur.push(next)
}
return cur
},[])
js两个数组交集,并集,差集
//数组求交集,并集,补集
let arr3 = [1,2,3,4,8]
let arr4 = [2,4,6,8]
//并集 Union
//let arr5 = arr3.concat(arr4)
//es6 数组合并新写法
let arr5 = [...arr3, ...arr4]
console.log([...new Set(arr5)])
//交集 intersect
let jiao = []
for(let i = 0; i < arr3.length; i++){
for(let j = 0; j < arr4.length; j++) {
if(arr3[i] === arr4[j]){
jiao.push(arr3[i])
}
}
}
console.log(jiao)
//交集 intersect es6
let arr6 = [...new Set(arr3)].filter(item => new Set(arr4).has(item))
console.log(arr6)
//补集/差集 difference = A - A ∩ B
//[...new Set(arr5)]
//A相对于B的差集
let difference = [...new Set(arr3)].filter(item => !new Set(arr4).has(item))
console.log(difference)
本文由 dealdot <dealdot#163.com> 创作, Full Stack Developer @ DeepBlue
本文最后编辑时间为: May 17, 2021 at 10:28 am
转载请注明来源