提升效率的JavaScript简写技巧有哪些(javascript,web开发)

时间:2024-04-18 16:25:20 作者 : 石家庄SEO 分类 : web开发
  • TAG :

提升效率的JavaScript简写技巧有哪些

简写技巧

当同时声明多个变量时,可简写成一行

//Longhandletx;lety=20;//Shorthandletx,y=20;

利用解构,可为多个变量同时赋值

//Longhandleta,b,c;a=5;b=8;c=12;//Shorthandlet[a,b,c]=[5,8,12];

巧用三元运算符简化if else

//Longhandletmarks=26;letresult;if(marks>=30){result='Pass';}else{result='Fail';}//Shorthandletresult=marks>=30?'Pass':'Fail';

使用||运算符给变量指定默认值

本质是利用了||运算符的特点,当前面的表达式的结果转成布尔值为false时,则值为后面表达式的结果

//LonghandletimagePath;letpath=getImagePath();if(path!==null&&path!==undefined&&path!==''){imagePath=path;}else{imagePath='default.jpg';}//ShorthandletimagePath=getImagePath()||'default.jpg';

使用&&运算符简化if语句

例如某个函数在某个条件为真时才调用,可简写

//Longhandif(isLoggedin){goToHomepage();}//ShorthandisLoggedin&&goToHomepage();

使用解构交换两个变量的值

letx='Hello',y=55;//Longhandconsttemp=x;x=y;y=temp;//Shorthand[x,y]=[y,x];

适用箭头函数简化函数

//Longhandfunctionadd(num1,num2){returnnum1+num2;}//Shorthandconstadd=(num1,num2)=>num1+num2;

需要注意箭头函数和普通函数的区别

使用字符串模板简化代码

使用模板字符串代替原始的字符串拼接

//Longhandconsole.log('Yougotamissedcallfrom'+number+'at'+time);//Shorthandconsole.log(`Yougotamissedcallfrom${number}at${time}`);

多行字符串也可使用字符串模板简化

//Longhandconsole.log('JavaScript,oftenabbreviatedasJS,isa\n'+'programminglanguagethatconformstothe\n'+'ECMAScriptspecification.JavaScriptishigh-level,\n'+'oftenjust-in-timecompiled,andmulti-paradigm.');//Shorthandconsole.log(`JavaScript,oftenabbreviatedasJS,isaprogramminglanguagethatconformstotheECMAScriptspecification.JavaScriptishigh-level,oftenjust-in-timecompiled,andmulti-paradigm.`);

对于多值匹配,可将所有值放在数组中,通过数组方法来简写

//Longhandif(value===1||value==='one'||value===2||value==='two'){//Executesomecode}//Shorthand1if([1,'one',2,'two'].indexOf(value)>=0){//Executesomecode}//Shorthand2if([1,'one',2,'two'].includes(value)){//Executesomecode}

巧用ES6对象的简洁语法

例如,当属性名和变量名相同时,可直接缩写为一个

letfirstname='Amitav';letlastname='Mishra';//Longhandletobj={firstname:firstname,lastname:lastname};//Shorthandletobj={firstname,lastname};

使用一元运算符简化字符串转数字

//Longhandlettotal=parseInt('453');letaverage=parseFloat('42.6');//Shorthandlettotal=+'453';letaverage=+'42.6';

使用repeat()方法简化重复一个字符串

//Longhandletstr='';for(leti=0;i<5;i++){str+='Hello';}console.log(str);//HelloHelloHelloHelloHello//Shorthand'Hello'.repeat(5);//想跟你说100声抱歉!'sorry\n'.repeat(100);

使用双星号代替Math.pow()

//Longhandconstpower=Math.pow(4,3);//64//Shorthandconstpower=4**3;//64

使用双波浪线运算符(~~)代替Math.floor()

//Longhandconstfloor=Math.floor(6.8);//6//Shorthandconstfloor=~~6.8;//6

需要注意,~~仅适用于小于2147483647的数字

巧用扩展操作符(...)简化代码

简化数组合并

letarr1=[20,30];//Longhandletarr2=arr1.concat([60,80]);//[20,30,60,80]//Shorthandletarr2=[...arr1,60,80];//[20,30,60,80]

单层对象的拷贝

letobj={x:20,y:{z:30}};//LonghandconstmakeDeepClone=(obj)=>{letnewObject={};Object.keys(obj).map(key=>{if(typeofobj[key]==='object'){newObject[key]=makeDeepClone(obj[key]);}else{newObject[key]=obj[key];}});returnnewObject;}constcloneObj=makeDeepClone(obj);//ShorthandconstcloneObj=JSON.parse(JSON.stringify(obj));//Shorthandforsinglelevelobjectletobj={x:20,y:'hello'};constcloneObj={...obj};

寻找数组中的最大和最小值

//Shorthandconstarr=[2,8,15,4];Math.max(...arr);//15Math.min(...arr);//2

使用for in和for of来简化普通for循环

letarr=[10,20,30,40];//Longhandfor(leti=0;i<arr.length;i++){console.log(arr[i]);}//Shorthand//forofloopfor(constvalofarr){console.log(val);}//forinloopfor(constindexinarr){console.log(arr[index]);}

简化获取字符串中的某个字符

letstr='jscurious.com';//Longhandstr.charAt(2);//c//Shorthandstr[2];//c

移除对象属性

letobj={x:45,y:72,z:68,p:98};//Longhanddeleteobj.x;deleteobj.p;console.log(obj);//{y:72,z:68}//Shorthandlet{x,p,...newObj}=obj;console.log(newObj);//{y:72,z:68}

使用arr.filter(Boolean)过滤掉数组成员的值falsey

letarr=[12,null,0,'xyz',null,-25,NaN,'',undefined,0.5,false];//LonghandletfilterArray=arr.filter(function(value){if(value)returnvalue;});//filterArray=[12,"xyz",-25,0.5]//ShorthandletfilterArray=arr.filter(Boolean);//filterArray=[12,"xyz",-25,0.5]
 </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:提升效率的JavaScript简写技巧有哪些的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:ajax的核心怎么理解下一篇:

14 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18