//方式一:使用set
function removeSame1(arr) {
return Array.from(new Set(arr))
}
//方式二:filter
function removeSame2(arr) {
return arr.filter((val,index) => {
return arr.indexOf(val)===index
});
}
//方式三:使用map
function removeSame3(arr) {
let m = new Map()
let obj = arr.reduce((begin,now)=>{
if(begin.has(now)) begin[now]
else begin[now] = 1
return begin
},m)
console.log(obj)
let res = []
for(let key in obj) {
res.push(key)
}
return res
}
2.1s打印一个数字
//方式一;直接for循环
function secondOne(num) {
for(let i=0;i<num;i++) {
setTimeout(() => {
console.log(i)
}, 1000);
}
}
//方式二:promise
function secondOne(i) {
return new Promise((resolve,reject)=>{
setTimeout(() => {
resolve(i)
}, 1000);
})
}
async function list () {
for(let i=0;i<5;i++) {
let num = await secondOne(i)
console.log(num)
}
}
list()
3.模拟sleep
function sleep(timer,fn) {
return new Promise((resolve,reject)=>{
setTimeout(() => {
resolve(fn())
}, timer*1000);
})
}
4.jsonp
function jsonp (src,callback) {
let oScript = document.createElement("script")
oScript.src = src//后端接口地址
document.body.appendChild(oScript)
window.callback = function(data) {
console.log("后端返回的数据",data)
}
}
5.下划线转换大写
function downLinetoUpper(str) {
//abc_def-->abcDef
let arr = str.split("_")
return arr.reduce((begin,now,index)=>{
if(index===0) return begin+now
let strs = now.split("")
strs[0] = strs[0].toUpperCase()
return begin+strs.join("")
},"")
}
6.url转换对象
function urlParams(str) {
str = str.split("?")[1]//截取参数部分字符串
arr = str.split("&")
return arr.reduce((begin,now)=>{
let res = now.split("=")
begin[res[0]] = res[1]
return begin
},{})
}
7.版本号比较
function compareId(id1,id2) {
//1.01 01.0001
let arr1 = id1.split(".")
let arr2 = id2.split(".")
let min = Math.min(arr1.length,arr2.length)
for(let i=0;i<min;i++) {
if(Number(arr1[i]>arr2[i])) return 1
else if(Number(arr1[i]<arr2[i])) return -1
}
for(let i=min;i<arr1.length;i++) {
if(Number(arr1[i])>0) return 1
}
for(let i=min;i<arr2.length;i++) {
if(Number(arr2[i])>0) return -1
}
return 0
}