8 个有用的JS技巧(推荐)
为了保证的可读性,本文采用意译而非直译。
想阅读更多优质文章请猛戳GitHub博客,一年百来篇优质文章等着你!
这些技巧可能大家大部分都用过了,如果用过就当作加深点映像,如果没有遇到过,就当作学会了几个技巧。
1.确保数组值
使用grid,需要重新创建原始数据,并且每行的列长度可能不匹配,为了确保不匹配行之间的长度相等,可以使用Array.fill方法。
letarray=Array(5).fill(''); console.log(array);//outputs(5)["","","","",""]
2.获取数组唯一值
ES6提供了从数组中提取惟一值的两种非常简洁的方法。不幸的是,它们不能很好地处理非基本类型的数组。在本文中,主要关注基本数据类型。
constcars=[ 'Mazda', 'Ford', 'Renault', 'Opel', 'Mazda' ] constuniqueWithArrayFrom=Array.from(newSet(cars)); console.log(uniqueWithArrayFrom);//outputs["Mazda","Ford","Renault","Opel"] constuniqueWithSpreadOperator=[...newSet(cars)]; console.log(uniqueWithSpreadOperator);//outputs["Mazda","Ford","Renault","Opel"]
3.使用展开运算符合并对象和对象数组
对象合并是很常见的事情,我们可以使用新的ES6特性来更好,更简洁的处理合并的过程。
//mergingobjects constproduct={name:'Milk',packaging:'Plastic',price:'5$'} constmanufacturer={name:'CompanyName',address:'TheCompanyAddress'} constproductManufacturer={...product,...manufacturer}; console.log(productManufacturer); //outputs{name:"CompanyName",packaging:"Plastic",price:"5$",address:"TheCompanyAddress"} //merginganarrayofobjectsintoone constcities=[ {name:'Paris',visited:'no'}, {name:'Lyon',visited:'no'}, {name:'Marseille',visited:'yes'}, {name:'Rome',visited:'yes'}, {name:'Milan',visited:'no'}, {name:'Palermo',visited:'yes'}, {name:'Genoa',visited:'yes'}, {name:'Berlin',visited:'no'}, {name:'Hamburg',visited:'yes'}, {name:'NewYork',visited:'yes'} ]; constresult=cities.reduce((accumulator,item)=>{ return{ ...accumulator, [item.name]:item.visited } },{}); console.log(result); /*outputs Berlin:"no" Genoa:"yes" Hamburg:"yes" Lyon:"no" Marseille:"yes" Milan:"no" NewYork:"yes" Palermo:"yes" Paris:"no" Rome:"yes" */
4.数组map的方法(不使用Array.Map)
另一种数组map的实现的方式,不用Array.map。
Array.from还可以接受第二个参数,作用类似于数组的map方法,用来对每个元素进行处理,将处理后的值放入返回的数组。如下:
constcities=[ {name:'Paris',visited:'no'}, {name:'Lyon',visited:'no'}, {name:'Marseille',visited:'yes'}, {name:'Rome',visited:'yes'}, {name:'Milan',visited:'no'}, {name:'Palermo',visited:'yes'}, {name:'Genoa',visited:'yes'}, {name:'Berlin',visited:'no'}, {name:'Hamburg',visited:'yes'}, {name:'NewYork',visited:'yes'} ]; constcityNames=Array.from(cities,({name})=>name); console.log(cityNames); //outputs["Paris","Lyon","Marseille","Rome","Milan","Palermo","Genoa","Berlin","Hamburg","NewYork"]
5.有条件的对象属性
不再需要根据一个条件创建两个不同的对象,可以使用展开运算符号来处理。
nstgetUser=(emailIncluded)=>{ return{ name:'John', surname:'Doe', ...emailIncluded&&{email:'john@doe.com'} } } constuser=getUser(true); console.log(user);//outputs{name:"John",surname:"Doe",email:"john@doe.com"} constuserWithoutEmail=getUser(false); console.log(userWithoutEmail);//outputs{name:"John",surname:"Doe"}
6.解构原始数据
有时候一个对象包含很多属性,而我们只需要其中的几个,这里可以使用解构方式来提取我们需要的属性。如一个用户对象内容如下:
constrawUser={ name:'John', surname:'Doe', email:'john@doe.com', displayName:'SuperCoolJohn', joined:'2016-05-05', image:'path-to-the-image', followers:45 ... }
我们需要提取出两个部分,分别是用户及用户信息,这时可以这样做:
letuser={},userDetails={}; ({name:user.name,surname:user.surname,...userDetails}=rawUser); console.log(user);//outputs{name:"John",surname:"Doe"} console.log(userDetails);//outputs{email:"john@doe.com",displayName:"SuperCoolJohn",joined:"2016-05-05",image:"path-to-the-image",followers:45}
7.动态属性名
早期,如果属性名需要是动态的,我们首先必须声明一个对象,然后分配一个属性。这些日子已经过去了,有了ES6特性,我们可以做到这一点。
constdynamic='email'; letuser={ name:'John', [dynamic]:'john@doe.com' } console.log(user);//outputs{name:"John",email:"john@doe.com"}
8.字符串插值
在用例中,如果正在构建一个基于模板的helper组件,那么这一点就会非常突出,它使动态模板连接容易得多。
constuser={ name:'John', surname:'Doe', details:{ email:'john@doe.com', displayName:'SuperCoolJohn', joined:'2016-05-05', image:'path-to-the-image', followers:45 } } constprintUserInfo=(user)=>{ consttext=`Theuseris${user.name}${user.surname}.Email:${user.details.email}.DisplayName:${user.details.displayName}.${user.name}has${user.details.followers}followers.` console.log(text); } printUserInfo(user); //outputs'TheuserisJohnDoe.Email:john@doe.com.DisplayName:SuperCoolJohn.Johnhas45followers.'
译者:前端小智
原文:https://devinduct.com/blogpost/26/8-useful-javascript-tricks
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。