记录分享下JavaScript7个简单实用的小技巧~
数组去重
const a = [...new Set([1,2,3,4,5,5,5])]
//[1,2,3,4,5]
过滤falsy值
从数组中过滤掉0、false、undefined、null、''、NaN
:
const a = [1,2,3,4,0,undefined,null,false,''].filter(Boolean)
//[ 1, 2, 3, 4 ]
创建空对象
可以使用{}创建一个对象,但该对象仍然有__proto__
和hasOwnProperty
以及其它对象方法。可以使用以下创建一个纯粹的空对象:
const dict = Object.create(null)
// dict.__proto__ === "undefined"
// No object properties exist until you add them
没有任何属性和方法,很纯粹
合并对象
使用解构:
const a = {name:'a'}
const b = {party:'b'}
const c = {interest:'c'}
const d = {...a,...b,...c}
//{ name: 'a', party: 'b', interest: 'c' }
函数参数强制需要
ES6为函数参数添加了默认值,只有函数传入参数严格===undefined时,才会使用参数默认值。
const isRequired = ()=> { throw new Error('param is required'); };
const hello = (name = isRequired()) => { console.log(`hello ${name}`) }
hello()
hello(undefined)
//以上两个调用均会报错
hello('xiaohong')
//hello xiaohong
解构赋值添加别名
ES6新增的解构十分使用,还能使用别名的方式用其它名称的变量。
const obj = {x:1}
const {x} = obj
const {x:antherName} = obj
console.log(x,antherName)
//1
//`
获取查询字符串参数
获取url里面的参数或者追加查询字符串,以前要用正则表达式,现在新增一个apiURLSearchParams
const urlParams = new URLSearchParams("q=URLUtils.searchParams&topic=api");
console.log(urlParams.has('topic')); // true
console.log(urlParams.get('topic')); // api
console.log(urlParams.getAll('topic')); // [ 'api' ]
console.log(urlParams.toString()); // q=URLUtils.searchParams&topic=api
urlParams.append("topic", "webdev");
console.log(urlParams.toString()); // q=URLUtils.searchParams&topic=api&topic=webdev