记录一些实用的小技巧-JS篇

1.16进制随机颜色

let color = '#'+Math.random().toString(16).slice(-6)

2.类型判断工具函数

function isType(target, type) {
  let targetType = Object.prototype.toString.call(target).slice(8, -1).toLowerCase()
  type = type.toLowerCase()
  return targetType === type
}
isType([],'array') //true

3.正则匹配两个字符间的内容

let str = '#javascript#html#css#'
let res = str.match(/#.*?#/)[0]

4.简洁的设置默认参数

if(!arr){
  arr = []
}
arr.push(1)

//能够这样写
(arr && (arr=[])).push(1)

5.reduce会更简洁

filter和map的组合使用可能不少人都会使用过,可是这样会进行两次遍历操做。能够使用reduce遍历一次完成一样的操做。javascript

reduce接受一个回调函数和一个默认值。css

回调函数接受两个参数,prev是上次返回值,curr是当前遍历值。在第一次遍历时,prev为默认值,每次遍历返回的prev都会在下一个遍历中取到。reduce所以也被叫作”累加函数“。html

let people = [{name:'Joe',age:18},{name:'Mike',age:19},{name:'Jack',age:20}]
people.fliter(p=>p.age < 20).map(p=>p.name)

//能够这样写
people.reduce((prev,curr)=>{
    if(age<20){
       prev.push(curr.name)
    }
    return prev
},[])

6.策略模式

使用策略模式来代替一堆的 if...else,让代码看起来更简洁java

if(type == = 'content'){
    getContent()
}else if(type === 'hot'){
    getHot()
}else if(type === 'rank'){
    getRank()
}
...

//能够这样写
let action = {
    content: getContent,
    hot: getHot,
    rank: getRank,
    ....
}
action[type]()

 7.JSON.stringify的其余参数

let str = {a:1,b:2,c:3}

//过滤
JSON.stringify(str, ['a'])   //"{"a":1}"

//格式化
JSON.stringify(str, null, 2)  
/*
"{
  "a": 1,
  "b": 2,
  "c": 3
}"
*/

8.获取月份的最后一天

new Date('2019','2',0).getDate()

 

部分来源于网络收集,不定时更新~网络

相关文章
相关标签/搜索