快来看JS的的几个常用算法(持续更新中)
数组去重
// 第一种方法
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
精确到指定位数(取小数第一位)
let num4=6.222;
console.log(num4.toFixed(1));//6.2
解构
let [rr,aa]=[1,2];
console.log(rr);//1
使用解构交换数值
[rr,aa]=[aa,rr];
console.log(rr);//2
判断数据类型
let ee=[1,12];
let ongjj={
name:'maomin'
}
function isType(arr) {
return Object.prototype.toString.call(arr)
}
console.log(isType(ee));//[object Array]
console.log(isType(ongjj));//[object Object]
字符串转化为对象
let stringobj='{"id":0,"name":"张三","age":12}';
let d3=JSON.parse(stringobj);
console.log(d3)//{id: 0, name: "张三", age: 12}
对象转化为字符串
let objj={
id:0,
name:'maomin'
}
let d4=JSON.stringify(objj)
console.log(d4);//{"id":0,"name":"maomin"}
字符串转化为数组
let stringww="a,b,c,d,e,f";
console.log(stringww.split(","))//["a", "b", "c", "d", "e", "f"]
数组转化为字符串
let arr9=['l','o','v','e'];
console.log(arr9.join('-'))
去除字符串指定符号
var stre="a,b,c,d";
function clear(str) {
str = str.replace(/,/g, "");//取消字符串中出现的所有逗号
return str;
}
console.log(clear(stre))//abcd
作者:Vam的金豆之路
主要领域:前端开发
我的微信:maomin9761
微信公众号:前端历劫之路