废话不多说,本文罗列一些比较常用或者实用的JavaScript代码片段,希望对大家有所帮助。1.三元运算符letsomeThingTrue=trueif(someThingTrue){handleTrue()}else{handleFalse()}******这里是简版******letsomeThingTrue=truesomeThingTrue?handleTrue():handleFalse()2.短路或操作constdefaultValue="SomeDefaultValue"letsomeValueNotSureOfItsExistance=nullletexpectingSomeValue=someValueNotSureOfItsExistance||defaultValueconsole.log(expectingSomeValue)//SomeDefaultValue3.conditionisestablishedletsomeValue=trueif(someValue){console.log('4.forconditionisestablished!')Loopfor(leti=0;i<1e2;i++){//换成i<100是不是很爽letsomeValues=[1,2,4]for(letvalinsomeValues){console.log(val)}letobj={'key1':'value1','key2':'value2','key3':'value3'}for(letkeyinobj){console.log(key)}5.从值到对象的映射letx='x',y='y'letobj={x,y}console.log(obj)//{x:"x",y:"y"}6.Object.entries()constcredits={producer:'大千世界',name:'前端小智',rating:9}constarr=Object.entries(credits)console.log(arr)***输出***[['producer','盛世之举'],['name','前端小智'],['rating',9]]7.object.values()constcredits={producer:'走向世界的大招',name:'前端小智',rating:9}constarr=Object.values(credits)console.log(arr)***output***['大千世界','前端小智',9]8.模板字面量letname='前端小智'letage=20varsomeStringConcatenateSomeVariable=`我是${name},今年是${age}`console.log(someStringConcatenateSomeVariable)9.解构赋值import{observable,action,runInAction}from'mobx';10.多行字符串letmultiLineString=`somestring\nwithmulti-lineof\ncharacters\n`console.log(multiLineString)11.Array.findshorthandconstpets=[{type:'Dog',name:'Max'},{type:'Cat',name:'Karl'},{type:'Dog',name:'Tommy'}]pet=pets.find(pet=>pet.type==='Dog'&&pet.name==='Tommy')console.log(pet)//{type:'Dog',name:'Tommy'}12.默认参数值的早期实践functionarea(h,w){if(!h){h=1;}if(!w){w=1;}returnh*w}ES6及以后练习functionarea(h=1,w=1){returnh*w}13。箭头函数letsayHello=(name)=>{return`Hello,${name}`}console.log(sayHello('前端小智'))简写如下:letsayHello=name=>`Hello,${name}`console.log(sayHello('前端小智'))14.隐式返回letsomeFuncThatReturnSomeValue=(value)=>{returnvalue+value}console.log(someFuncThatReturnSomeValue('前端小智'))简写如下:让一些乐趣cThatReturnSomeValue=(value)=>(value+value)console.log(someFuncThatReturnSomeValue('FrontendXiaozhi'))15.函数必须有参数值functionmustHavePatamMethod(param){if(param===undefined){thrownewError('HeyYoumustPutsomeparam!');}returnparam;}像这样覆盖:mustHaveCheck=()=>{thrownewError('Missingparameter!')}methodShoudHaveParam=(param=mustHaveCheck())=>{returnparam}16.charAt()shorthand'SampleString'.charAt(0)//S//'SampleString'[0]的简写17.条件函数调用functionfn1(){console.log('IamFunction1')}functionfn2(){console.log('IamFunction2')}/*长写法*/letcheckValue=3;if(checkValue===3){fn1()}else{fn2()}短写法:(checkValue===3?fn1:fn2)()17.Math.Floorshorthandletval='123.95'console.log(Math.floor(val))//常规写法console.log(~~val)//shorthand18.Math.powshorthandMath.pow(2,3)//8//简写2**3//819。将字符串转为数字constnum1=parseInt('100')//简写console.log(+"100")console.log(+"100.2")20.&&operationletvalue=1;if(value===1)console.log('Valueisone')//ORInshortvalue&&console.log('Valueisone')21.toString简写letsomeNumber=123console.log(someNumber.toString())//"123"//shorthandconsole.log(`${someNumber}`)//"123"22.optionalchainoperator(comingsoon)有一个新提案在ECMAScript中,值得了解letsomeUser={name:'Jack'}letzip=someUser?.address?.zip//可选链接,如果zip未定义,像Swift一样不会引发错误。该语法还支持函数和构造函数调用letaddress=getAddressByZip.?(12345)如果getAddressByZip是调用它的函数,否则表达式将被评估为未定义。23、使用对象方法替换switch语法default:drink='Unknownjuice!'}console.log(drink)//bananajuice作者:xor译者:前端小智来源:medium原文:https://medium.com/javascript-in-plain-english/some-js-shortcuts-82bc2f56146e本文转载自微信公众号“大招天下”,可通过以下二维码关注。转载请联系大千世界公众号。
