1.添加对象属性值
给对象添加属性,名称动态变化怎么办?let obj = {}; let index = 1; let key = `topic${index}`; obj[key] = 'topic';为什么要创建一个额外的变量?你不知道 ES6 中的对象属性名可以使用表达式吗?
let obj = {}; let index = 1; obj[`topic${index}`] = 'topic';2.列表搜索
// 堆代码 duidaima.com const a = [1, 2, 3, 4, 5] const result = a.filter((item) => { return item === 3 }) console.log('result', result)但是,如果是精确搜索,则需要使用ES6中的find
const a = [1,2,3,4,5]; const result = a.find( item =>{ return item === 3 } )3.获取对象属性值
const name = obj && obj.name你可以在 ES6 中使用可选的链接运算符:
const name = obj?.name
const deps = { 'data01':[1,2,3], 'data02':[5,8,12], 'data03':[5,14,79], 'data04':[3,64,105], } let member = []; for (let item in deps){ const value = deps[item]; if(Array.isArray(value)){ member = [...member,...value] } } member = [...new Set(member)]这时候,我好像听到前端组长开始骂了:
// 堆代码 duidaima.com const deps = { 'data01':[1,2,3], 'data02':[5,8,12], 'data03':[5,14,79], 'data04':[3,64,105], } let member = Object.values(deps).flat(Infinity);Infinity 用作平面参数,因此您不需要知道平面数组的维度。
if( type == 1 || type == 2 || type == 3 || type == 4 || ){ //... }改进后可简写为:
const condition = [1, 2, 3, 4] const type = 11 if (condition.includes(type)) { console.log('ok') }6.判断输入框不为空
if(value !== null && value !== undefined && value !== ''){ //... }可以改进为:
if((value??'') !== ''){ //... }是不是省了很多代码,惊喜还是意外?
const name = obj && obj.name改进后:
const name = obj?.name
fconst fn1 = () =>{ return new Promise((resolve, reject) => { setTimeout(() => { resolve(1); }, 300); }); } const fn2 = () =>{ return new Promise((resolve, reject) => { setTimeout(() => { resolve(2); }, 600); }); } const fn = () =>{ fn1().then(res1 =>{ console.log(res1);// 1 fn2().then(res2 =>{ console.log(res2) }) }) };看着这样的代码,我仿佛看到了前端组长轻蔑的眼神。这么写,跟回调地狱有什么区别?
const fn = async () =>{ const res1 = await fn1(); const res2 = await fn2(); console.log(res1);// 1 console.log(res2);// 2 }代码一下子简洁了许多,总算松了一口气。
const fn = () =>{ Promise.all([fn1(),fn2()]).then(res =>{ console.log(res);// [1,2] }) }最后