本文來(lái)自于:葡萄城控件技術(shù)團(tuán)隊(duì)博客
本文來(lái)源于多年的 JavaScript 編碼技術(shù)經(jīng)驗(yàn)怪蔑,適合所有正在使用 JavaScript 編程的開(kāi)發(fā)人員閱讀乃秀。
本文的目的在于幫助大家更加熟練的運(yùn)用 JavaScript 語(yǔ)言來(lái)進(jìn)行開(kāi)發(fā)工作脂信。
文章將分成初級(jí)篇和高級(jí)篇兩部分,分別進(jìn)行介紹厂庇。
初級(jí)篇
1椒振、三目運(yùn)算符
下面是一個(gè)很好的例子晰骑,將一個(gè)完整的 if 語(yǔ)句彼绷,簡(jiǎn)寫為一行代碼丐黄。
const x = 20;
let answer;if(x > 10) {
answer= 'greater than 10';
}else{
answer= 'less than 10';
}
簡(jiǎn)寫為:
const answer = x > 10 ?'greater than 10' : 'less than 10';
2斋配、循環(huán)語(yǔ)句
當(dāng)使用純 JavaScript(不依賴外部庫(kù),如 jQuery 或 lodash)時(shí)灌闺,下面的簡(jiǎn)寫會(huì)非常有用许起。
for(let i = 0; i < allImgs.length; i++)
簡(jiǎn)寫為:
for(letindexofallImgs)
下面是遍歷數(shù)組 forEach 的簡(jiǎn)寫示例:
functionlogArrayElements(element, index, array) {
console.log("a[" + index + "] = " +element);
}
[2, 5, 9].forEach(logArrayElements);//logs://a[0] = 2//a[1] = 5//a[2] = 9
3、聲明變量
在函數(shù)開(kāi)始之前菩鲜,對(duì)變量進(jìn)行賦值是一種很好的習(xí)慣园细。在申明多個(gè)變量時(shí):
let x;
let y;
let z= 3;
可以簡(jiǎn)寫為:
let x, y, z=3;
4、if 語(yǔ)句
在使用 if 進(jìn)行基本判斷時(shí)接校,可以省略賦值運(yùn)算符猛频。
if(likeJavaScript ===true)
簡(jiǎn)寫為:
if(likeJavaScript)
5、十進(jìn)制數(shù)
可以使用科學(xué)計(jì)數(shù)法來(lái)代替較大的數(shù)據(jù)蛛勉,如可以將 10000000 簡(jiǎn)寫為 1e7鹿寻。
for(let i = 0; i < 10000; i++) { }
簡(jiǎn)寫為:
for(let i = 0; i <1e7; i++) { }
6、多行字符串
如果需要在代碼中編寫多行字符串诽凌,就像下面這樣:
const lorem = 'Lorem ipsum dolor sit amet, consectetur\n\t'
+ 'adipisicing elit, sed do eiusmod tempor incididunt\n\t'
+ 'ut labore et dolore magna aliqua. Ut enim ad minim\n\t'
+ 'veniam, quis nostrud exercitation ullamco laboris\n\t'
+ 'nisi ut aliquip ex ea commodo consequat. Duis aute\n\t'
+ 'irure dolor in reprehenderit in voluptate velit esse.\n\t'
但是還有一個(gè)更簡(jiǎn)單的方法毡熏,只使用引號(hào):
const lorem =`Lorem ipsum dolor sit amet, consectetur
adipisicing elit, seddoeiusmod tempor incididunt
ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute
irure dolorinreprehenderitinvoluptate velit esse.`
高級(jí)篇
1、變量賦值
當(dāng)將一個(gè)變量的值賦給另一個(gè)變量時(shí)侣诵,首先需要確保原值不是 null痢法、未定義的或空值。
可以通過(guò)編寫一個(gè)包含多個(gè)條件的判斷語(yǔ)句來(lái)實(shí)現(xiàn):
if(variable1 !==null|| variable1 !== undefined || variable1 !== '') {
let variable2=variable1;
}
或者簡(jiǎn)寫為以下的形式:
const variable2 = variable1? ||'new';
可以將下面的代碼粘貼到es6console中杜顺,自己測(cè)試:
let variable1;
let variable2= variable1? || '';
console.log(variable2=== '');//prints truevariable1 = 'foo';
variable2= variable1? || '';
console.log(variable2);//prints foo
2财搁、默認(rèn)值賦值
如果預(yù)期參數(shù)是 null 或未定義,則不需要寫六行代碼來(lái)分配默認(rèn)值躬络。我們可以只使用一個(gè)簡(jiǎn)短的邏輯運(yùn)算符尖奔,只用一行代碼就能完成相同的操作。
let dbHost;if(process.env.DB_HOST) {
dbHost=process.env.DB_HOST;
}else{
dbHost= 'localhost';
}
簡(jiǎn)寫為:
const dbHost =process.env.DB_HOST || 'localhost';
3穷当、對(duì)象屬性
ES6 提供了一個(gè)很簡(jiǎn)單的辦法提茁,來(lái)分配屬性的對(duì)象。如果屬性名與 key 名相同馁菜,則可以使用簡(jiǎn)寫茴扁。
const obj = { x:x, y:y };
簡(jiǎn)寫為:
const obj = { x, y };
4、箭頭函數(shù)
經(jīng)典函數(shù)很容易讀寫火邓,但是如果把它們嵌套在其它函數(shù)中進(jìn)行調(diào)用時(shí)丹弱,整個(gè)函數(shù)就會(huì)變得有些冗長(zhǎng)和混亂。這時(shí)候可以使用箭頭函數(shù)來(lái)簡(jiǎn)寫:
functionsayHello(name) {
console.log('Hello', name);
}
setTimeout(function() {
console.log('Loaded')
},2000);
list.forEach(function(item) {
console.log(item);
});
簡(jiǎn)寫為:
sayHello = name => console.log('Hello', name);
setTimeout(()=> console.log('Loaded'), 2000);
list.forEach(item=> console.log(item));
5铲咨、隱式返回值
返回值是我們通常用來(lái)返回函數(shù)最終結(jié)果的關(guān)鍵字躲胳。只有一個(gè)語(yǔ)句的箭頭函數(shù),可以隱式返回結(jié)果(函數(shù)必須省略括號(hào)({ })纤勒,以便省略返回關(guān)鍵字)坯苹。
要返回多行語(yǔ)句(例如對(duì)象文本),需要使用()而不是{ }來(lái)包裹函數(shù)體摇天。這樣可以確保代碼以單個(gè)語(yǔ)句的形式進(jìn)行求值粹湃。
functioncalcCircumference(diameter) {returnMath.PI *diameter
}
簡(jiǎn)寫為:
calcCircumference = diameter =>(
Math.PI*diameter;
)
6、默認(rèn)參數(shù)值
可以使用 if 語(yǔ)句來(lái)定義函數(shù)參數(shù)的默認(rèn)值泉坐。ES6 中規(guī)定了可以在函數(shù)聲明中定義默認(rèn)值为鳄。
functionvolume(l, w, h) {if(w ===undefined)
w= 3;if(h ===undefined)
h= 4;returnl * w *h;
}
簡(jiǎn)寫為:
volume = (l, w = 3, h = 4 ) => (l * w *h);
volume(2)//output: 24
7、模板字符串
過(guò)去我們習(xí)慣了使用“+”將多個(gè)變量轉(zhuǎn)換為字符串腕让,但是有沒(méi)有更簡(jiǎn)單的方法呢孤钦?
ES6 提供了相應(yīng)的方法,我們可以使用反引號(hào)和 $ { } 將變量合成一個(gè)字符串纯丸。
const welcome = 'You have logged in as ' + first + ' ' + last + '.'const db= 'http://' + host + ':' + port + '/' + database;
簡(jiǎn)寫為:
const welcome = `You have loggedinas ${first} ${last}`;
const db= `http://${host}:${port}/${database}`;
8偏形、解構(gòu)賦值
解構(gòu)賦值是一種表達(dá)式,用于從數(shù)組或?qū)ο笾锌焖偬崛傩灾稻醣牵①x給定義的變量俊扭。
在代碼簡(jiǎn)寫方面,解構(gòu)賦值能達(dá)到很好的效果坠陈。
const observable = require('mobx/observable');
const action= require('mobx/action');
const runInAction= require('mobx/runInAction');
const store=this.props.store;
const form=this.props.form;
const loading=this.props.loading;
const errors=this.props.errors;
const entity=this.props.entity;
簡(jiǎn)寫為:
import { observable, action, runInAction } from 'mobx';
const { store, form, loading, errors, entity }=this.props;
甚至可以指定自己的變量名:
const { store, form, loading, errors, entity:contact } =this.props;
9萨惑、展開(kāi)運(yùn)算符
展開(kāi)運(yùn)算符是在 ES6 中引入的,使用展開(kāi)運(yùn)算符能夠讓 JavaScript 代碼更加有效和有趣仇矾。
使用展開(kāi)運(yùn)算符可以替換某些數(shù)組函數(shù)咒钟。
//joining arraysconst odd = [1, 3, 5];
const nums= [2 ,4 , 6].concat(odd);//cloning arraysconst arr = [1, 2, 3, 4];
const arr2= arr.slice( )
簡(jiǎn)寫為:
//joining arraysconstodd= [1, 3, 5];
const nums= [2 ,4 , 6, ...odd];console.log(nums);//[ 2, 4, 6, 1, 3, 5 ]//cloning arraysconstarr= [1, 2, 3, 4];
const arr2= [...arr];
和 concat( ) 功能不同的是,用戶可以使用擴(kuò)展運(yùn)算符在任何一個(gè)數(shù)組中插入另一個(gè)數(shù)組若未。
constodd= [1, 3, 5];
const nums= [2, ...odd, 4 , 6];
也可以將展開(kāi)運(yùn)算符和 ES6 解構(gòu)符號(hào)結(jié)合使用:
const { a, b, ...z } = { a: 1, b: 2, c: 3, d: 4};
console.log(a)//1console.log(b)//2console.log(z)//{ c: 3, d: 4 }
10朱嘴、強(qiáng)制參數(shù)
默認(rèn)情況下,如果不向函數(shù)參數(shù)傳值粗合,那么 JavaScript 會(huì)將函數(shù)參數(shù)設(shè)置為未定義萍嬉。其它一些語(yǔ)言則會(huì)發(fā)出警告或錯(cuò)誤。要執(zhí)行參數(shù)分配隙疚,可以使用if語(yǔ)句拋出未定義的錯(cuò)誤壤追,或者可以利用“強(qiáng)制參數(shù)”。
functionfoo(bar) {if(bar ===undefined) {thrownewError('Missing parameter!');
}returnbar;
}
簡(jiǎn)寫為:
mandatory = ( ) =>{thrownewError('Missing parameter!');
}
foo= (bar = mandatory( )) =>{returnbar;
}
11供屉、Array.find
如果你曾經(jīng)編寫過(guò)普通 JavaScript 中的 find 函數(shù)行冰,那么你可能使用了 for 循環(huán)溺蕉。在 ES6 中,介紹了一種名為 find()的新數(shù)組函數(shù)悼做,可以實(shí)現(xiàn) for 循環(huán)的簡(jiǎn)寫疯特。
const pets =[
{ type:'Dog', name: 'Max'},
{ type:'Cat', name: 'Karl'},
{ type:'Dog', name: 'Tommy'},
]functionfindDog(name) {for(let i = 0; i
}
}
}
簡(jiǎn)寫為:
pet = pets.find(pet => pet.type ==='Dog' && pet.name === 'Tommy');
console.log(pet);//{ type: 'Dog', name: 'Tommy' }
12、Object [key]
雖然將 foo.bar 寫成 foo ['bar'] 是一種常見(jiàn)的做法肛走,但是這種做法構(gòu)成了編寫可重用代碼的基礎(chǔ)漓雅。
請(qǐng)考慮下面這個(gè)驗(yàn)證函數(shù)的簡(jiǎn)化示例:
functionvalidate(values) {if(!values.first)returnfalse;if(!values.last)returnfalse;returntrue;
}
console.log(validate({first:'Bruce',last:'Wayne'}));//true
上面的函數(shù)完美的完成驗(yàn)證工作。但是當(dāng)有很多表單朽色,則需要應(yīng)用驗(yàn)證邻吞,此時(shí)會(huì)有不同的字段和規(guī)則。如果可以構(gòu)建一個(gè)在運(yùn)行時(shí)配置的通用驗(yàn)證函數(shù)葫男,會(huì)是一個(gè)好選擇抱冷。
//object validation rulesconst schema ={
first: {
required:true},
last: {
required:true}
}//universal validation functionconst validate = (schema, values) =>{for(fieldinschema) {if(schema[field].required) {if(!values[field]) {returnfalse;
}
}
}returntrue;
}
console.log(validate(schema, {first:'Bruce'}));//falseconsole.log(validate(schema, {first:'Bruce',last:'Wayne'}));//true
現(xiàn)在有了這個(gè)驗(yàn)證函數(shù),我們就可以在所有窗體中重用梢褐,而無(wú)需為每個(gè)窗體編寫自定義驗(yàn)證函數(shù)徘层。
13、雙位操作符
位操作符是 JavaScript 初級(jí)教程的基本知識(shí)點(diǎn)利职,但是我們卻不常使用位操作符趣效。因?yàn)樵诓惶幚矶M(jìn)制的情況下,沒(méi)有人愿意使用 1 和 0猪贪。
但是雙位操作符卻有一個(gè)很實(shí)用的案例跷敬。你可以使用雙位操作符來(lái)替代 Math.floor( )。雙否定位操作符的優(yōu)勢(shì)在于它執(zhí)行相同的操作運(yùn)行速度更快热押。
Math.floor(4.9) === 4//true
簡(jiǎn)寫為:
~~4.9 === 4//true
總結(jié)
上述是一些常用的 JavaScript 簡(jiǎn)寫技巧西傀,如果有其它未提及的簡(jiǎn)寫技巧,也歡迎大家補(bǔ)充桶癣。
原文鏈接:https://www.sitepoint.com/shorthand-javascript-techniques/
轉(zhuǎn)載請(qǐng)注明出自:葡萄城控件
關(guān)于葡萄城
葡萄城成立于1980年拥褂,是全球最大的控件提供商,世界領(lǐng)先的企業(yè)應(yīng)用定制工具牙寞、企業(yè)報(bào)表和商業(yè)智能解決方案提供商饺鹃,為超過(guò)75%的全球財(cái)富500強(qiáng)企業(yè)提供服務(wù)。葡萄城于1988年在中國(guó)設(shè)立研發(fā)中心间雀,在全球化產(chǎn)品的研發(fā)過(guò)程中悔详,不斷適應(yīng)中國(guó)市場(chǎng)的本地需求,并為軟件企業(yè)和各行業(yè)的信息化提供優(yōu)秀的軟件工具和咨詢服務(wù)惹挟。