// 第一种方法
let arr = [1,1,2,3,4];
function fun(v) {
return Array.from(new Set(v))
}
console.log(fun(arr)) //[1,2,3,4]
// 第二种方法
let qc= [...new Set(arr)]
console.log(qc) //[1,2,3,4]
数组并集
let arr0 = ['a','b','c'];
let arr2 = ['c','d'];
let a=new Set(arr0);
let b=new Set(arr2);
let bj = new Set([...a,...b]);
console.log(bj);//{“a”, “b”, “c”, “d”}
数组交集
let jj = new Set([…a].filter(x=>b.includes(x)));
console.log(jj);//{“c”}
数组差集
let cj = new Set([...a].filter(x=>!b.includes(x)));
console.log(cj);//{“a”, “b”}
统计数组相同项的个数
let arr6=['a','a','a','b','c','c'];
let arr6obj=arr6.reduce(function(obj,name){
obj[name]=obj[name]?++obj[name]:1;
return obj;
},{})
console.log(arr6obj)// {a: 3, b: 1, c: 2}
数组方法reduce()实现filter、map
let arr7=[2,3,10];
const arro=arr7.reduce(function(list,num){
num=num*2;
if(num>=20){
list.push(num)
}
return list;
},[])
console.log(arro);//[20]
字符串转换为数字
let num1='1' * 1;
console.log(typeof num1) //number
使用Boolean过滤数组中的所有假值
let jz=[0,null,false,NaN,1,2];
const filter1=arr1=>arr1.filter(Boolean);
console.log(filter1(jz)) //[1,2]
取整
let num2=1.223;
console.log(num2|0);//1
判断奇偶
let num3=3;
console.log(!!(num3 & 1));//true
更多内容请见原文,原文转载自:https://blog.csdn.net/weixin_44519496/article/details/120074271
原创文章,作者:Carrie001128,如若转载,请注明出处:https://blog.ytso.com/276252.html