JavaScript代碼優(yōu)化技巧

1舞终、 帶有多個(gè)條件的 if 語(yǔ)句

把多個(gè)值放在一個(gè)數(shù)組中穴店,然后調(diào)用數(shù)組的 includes 方法。

//longhand

if(x ==='abc'|| x ==='def'|| x ==='ghi'|| x ==='jkl') {//logic}

//shorthand

if(['abc','def','ghi','jkl'].includes(x)) {//logic}

2、簡(jiǎn)化 if true...else

對(duì)于不包含大邏輯的 if-else 條件衔憨,可以使用下面的快捷寫(xiě)法。我們可以簡(jiǎn)單地使用三元運(yùn)算符來(lái)實(shí)現(xiàn)這種簡(jiǎn)化袄膏。

// Longhand

let test: boolean;

if(x > 100) {test=true;}else{test=false;}

// Shorthand

let test= (x > 10) ?true:false;//或者我們也可以直接用let test= x > 10;console.log(test);

如果有嵌套的條件践图,可以這么做。

let x =300,

test2 = (x >100) ?'greater than 100': (x <50) ?'less 50':'between 50 and 100';

console.log(test2);// "greater than 100"

3沉馆、聲明變量

當(dāng)我們想要聲明兩個(gè)具有相同的值或相同類(lèi)型的變量時(shí)码党,可以使用這種簡(jiǎn)寫(xiě)。

//Longhand?

let test1;

let test2 =1;

//Shorthand?

let test1, test2 =1;

4斥黑、null揖盘、undefined 和空值檢查

當(dāng)我們創(chuàng)建了新變量,有時(shí)候想要檢查引用的變量是不是為非 null 或 undefined心赶。

JavaScript 確實(shí)有一個(gè)很好的快捷方式來(lái)實(shí)現(xiàn)這種檢查扣讼。

// Longhand

if(test1 !==null|| test1 !==undefined|| test1 !=='') {let test2 = test1;}

// Shorthand

let test2 = test1 ||'';

5缺猛、?null 檢查和默認(rèn)賦值

let test1 =null,

test2 = test1 ||'';

console.log("null check", test2);// 輸出 ""

6缨叫、?undefined 檢查和默認(rèn)賦值

let test1 =undefined,

test2 = test1 ||'';

console.log("undefined check", test2);// 輸出 ""

一般值檢查

let test1 ='test',

test2 = test1 ||'';

console.log(test2);// 輸出: 'test'

另外,對(duì)于上述的 4荔燎、5耻姥、6 點(diǎn),都可以使用?? 操作符有咨。

如果左邊值為 null 或 undefined琐簇,就返回右邊的值。默認(rèn)情況下座享,它將返回左邊的值婉商。

const test=null??'default';

console.log(test);// 輸出結(jié)果: "default"

const test1 =0??2;

console.log(test1);// 輸出結(jié)果: 0

7、給多個(gè)變量賦值

當(dāng)我們想給多個(gè)不同的變量賦值時(shí)渣叛,這種技巧非常有用丈秩。

//Longhand?

let test1, test2, test3;

test1 = 1;

test2 = 2;

test3 = 3;

//Shorthand?

let [test1, test2, test3] = [1, 2, 3];

8、簡(jiǎn)便的賦值操作符

在編程過(guò)程中淳衙,我們要處理大量的算術(shù)運(yùn)算符蘑秽。這是 JavaScript 變量賦值操作符的有用技巧之一。

// Longhand

test1 = test1 + 1;

test2 = test2 - 1;

test3 = test3 * 20;

// Shorthand

test1++;

test2--;

test3 *= 20;

9箫攀、?if 判斷值是否存在

這是我們都在使用的一種常用的簡(jiǎn)便技巧肠牲,在這里仍然值得再提一下。

// Longhand

if(test1 ===true)or if(test1 !=="")or if(test1 !==null)// Shorthand //檢查空字符串靴跛、null或者undefined

if(test1)

注意:如果 test1 有值缀雳,將執(zhí)行 if 之后的邏輯,這個(gè)操作符主要用于 null 或 undefinded 檢查梢睛。

10肥印、?用于多個(gè)條件判斷的 && 操作符

如果只在變量為 true 時(shí)才調(diào)用函數(shù)严拒,可以使用 && 操作符。

//Longhand?

if(test1) { callMethod(); }?

//Shorthand?

test1 &&callMethod();

11竖独、for each 循環(huán)

這是一種常見(jiàn)的循環(huán)簡(jiǎn)化技巧裤唠。

// Longhand

for(vari =0; i < testData.length; i++)

// Shorthand

for(letiintestData) or for(letioftestData)

遍歷數(shù)組的每一個(gè)變量。

function testData(element, index, array){console.log('test['+ index +'] = '+ element);}

[11,24,32].forEach(testData);// logs: test[0] = 11, test[1] = 24, test[2] = 32

12莹痢、比較后返回

我們也可以在 return 語(yǔ)句中使用比較种蘸,它可以將 5 行代碼減少到 1 行。

// Longhand

let test;functioncheckReturn(){

if(!(test ===undefined)) {returntest;}else{returncallMe('test');? ? }}

var data = checkReturn();

console.log(data);//output test

functioncallMe(val){console.log(val);}

// Shorthand

function checkReturn(){returntest || callMe('test');}

13竞膳、?箭頭函數(shù)

//Longhand?

function add(a, b){returna + b;}?

//Shorthand?

const add =(a, b) =>a + b;

更多例子:

function callMe(name){console.log('Hello', name);}

callMe =name=>console.log('Hello', name);

14航瞭、簡(jiǎn)短的函數(shù)調(diào)用

我們可以使用三元操作符來(lái)實(shí)現(xiàn)多個(gè)函數(shù)調(diào)用。

// Longhand

function test1(){console.log('test1');};

functiontest2(){console.log('test2');};

var test3 =1;

if(test3 ==1) {? test1();}else{? test2();}

// Shorthand(test3 ===1? test1:test2)();

15坦辟、switch 簡(jiǎn)化

我們可以將條件保存在鍵值對(duì)象中刊侯,并根據(jù)條件來(lái)調(diào)用它們。

// Longhand

switch (data) {

? case 1:? ? test1();?

?break;??

case 2:? ? test2();??

break;??

case 3:? ? test();??

break;??

// ...}

// Shorthand

var data = {??

1: test1,?

2: test2,??

3: test};

data[something] && data[something]();

16锉走、隱式返回

通過(guò)使用箭頭函數(shù)滨彻,我們可以直接返回值,不需要 return 語(yǔ)句挪蹭。

//longhand

function

calculate(diameter){

return Math.PI * diameter

}

//shorthand

calculate =diameter=>(Math.PI * diameter;)

17亭饵、?指數(shù)表示法

// Longhand

for(vari =0; i <10000; i++) { ... }

// Shorthand

for(vari =0; i <1e4; i++) {

18、默認(rèn)參數(shù)值

//Longhand

function add(test1, test2){

if(test1 ===undefined)

test1 =1;

if(test2 ===undefined)

test2 =2;

return test1 + test2;

}

//shorthand

add =(test1 =1, test2 =2) =>(test1 + test2);

add()//輸出結(jié)果: 3

19梁厉、延展操作符簡(jiǎn)化

//longhand

// 使用concat連接數(shù)組

const data= [1,2,3];

const test = [4,5,6].concat(data);

//shorthand

// 連接數(shù)組

const data= [1,2,3];

consttest = [4,5,6, ...data];

console.log(test);// [ 4, 5, 6, 1, 2, 3]

我們也可以使用延展操作符進(jìn)行克隆辜羊。

//longhand

// 克隆數(shù)組

const test1 = [1,2,3];

const test2 = test1.slice()

//shorthand//克隆數(shù)組

const test1 = [1,2,3];

const test2 = [...test1];

20、模板字面量

如果你厭倦了使用 + 將多個(gè)變量連接成一個(gè)字符串词顾,那么這個(gè)簡(jiǎn)化技巧將讓你不再頭痛八秃。

//longhand

const welcome ='Hi '+ test1 +' '+ test2 +'.'

//shorthand

const welcome =`Hi${test1}${test2}`;

21、跨行字符串

當(dāng)我們?cè)诖a中處理跨行字符串時(shí)肉盹,可以這樣做昔驱。

//longhand

const data ='abc abc abc abc abc abc\n\t'+'test test,test test test test\n\t'

//shorthand

const data = `abc abc abc abc abc abc

test test,test test test test`

22、對(duì)象屬性賦值

let test1 ='a';

let test2 ='b';

//Longhand?

let obj = {test1: test1,test2: test2};

//Shorthand?

let obj = {test1, test2};

23垮媒、將字符串轉(zhuǎn)成數(shù)字

//Longhand?

let test1 =parseInt('123');

let test2 =parseFloat('12.3');

//Shorthand?

let test1 = +'123';

let test2 = +'12.3';

24舍悯、解構(gòu)賦值

//longhand

const test1 =this.data.test1;

const test2 =this.data.test2;

const test2 =this.data.test3;

//shorthand

const{ test1, test2, test3 } =this.data;

25、數(shù)組 find 簡(jiǎn)化

當(dāng)我們有一個(gè)對(duì)象數(shù)組睡雇,并想根據(jù)對(duì)象屬性找到特定對(duì)象萌衬,find 方法會(huì)非常有用。

const data= [{

type:'test1',name:'abc'? ??

},? ? {

type:'test2',name:'cde'? ??

},? ? {

type:'test1',name:'fgh'? ??

},]

function findtest1(name) {

for(let i =0; i data.type ==='test1'&&data.name ==='fgh');

console.log(filteredData);

// { type: 'test1', name: 'fgh' }

26它抱、條件查找簡(jiǎn)化

如果我們要基于不同的類(lèi)型調(diào)用不同的方法秕豫,可以使用多個(gè) else if 語(yǔ)句或 switch,但有沒(méi)有比這更好的簡(jiǎn)化技巧呢?

// Longhand

if(type==='test1') {??

test1();

}else if(type==='test2') {??

test2();

}elseif(type==='test3') {

test3();

}elseif(type==='test4') {??

test4();

}else{

thrownewError('Invalid value '+type);

}

// Shorthand

var types = {??

test1: test1,??

test2: test2,??

test3: test3,??

test4: test4

};

var func = types[type];

(!func) &&throw new Error('Invalid value '+type); func();

27混移、indexOf 的按位操作簡(jiǎn)化

在查找數(shù)組的某個(gè)值時(shí)祠墅,我們可以使用 indexOf() 方法。但有一種更好的方法歌径,讓我們來(lái)看一下這個(gè)例子毁嗦。

//longhand

if(arr.indexOf(item) >-1) {

// item found?

}

if(arr.indexOf(item) ===-1) {

// item not found

}

//shorthand

if(~arr.indexOf(item)) {

// item found

}

if(!~arr.indexOf(item)) {

// item not found

}

按位 ( ~ ) 運(yùn)算符將返回 true(-1 除外),反向操作只需要!~回铛。另外狗准,也可以使用 include() 函數(shù)。

if(arr.includes(item)) {//如果找到項(xiàng)目茵肃,則為true}

28腔长、Object.entries()

這個(gè)方法可以將對(duì)象轉(zhuǎn)換為對(duì)象數(shù)組。

const data= { test1:'abc', test2:'cde', test3:'efg'};

const arr = Object.entries(data);

console.log(arr);

/** Output:

[ ['test1','abc'],['test2','cde'],['test3','efg']

]

**/

29验残、Object.values()

這也是 ES8 中引入的一個(gè)新特性捞附,它的功能類(lèi)似于 Object.entries(),只是沒(méi)有鍵您没。

const data = {test1:'abc',test2:'cde'};

const arr =Object.values(data);

console.log(arr);

/** Output:[ 'abc', 'cde']**/

30鸟召、雙重按位操作

// Longhand

Math.floor(1.9) ===1// true

// Shorthand

~~1.9===1// true

31、重復(fù)字符串多次

為了重復(fù)操作相同的字符紊婉,我們可以使用 for 循環(huán)药版,但其實(shí)還有一種簡(jiǎn)便的方法辑舷。

//longhand?

lettest='';

for(let i = 0; i < 5; i ++) {

test+='test ';

}?

console.log(str); //test test test test test

//shorthand?

'test '.repeat(5);

32喻犁、查找數(shù)組的最大值和最小值

const arr = [1,2,3];

Math.max(…arr);// 3

Math.min(…arr);// 1

33、獲取字符串的字符

let str ='abc';

//Longhand?

str.charAt(2);// c

//Shorthand?

str[2];// c

34何缓、?指數(shù)冪簡(jiǎn)化

//longhand

Math.pow(2,3);// 8

//shorthand

2**3// 8

本文完~

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末肢础,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子碌廓,更是在濱河造成了極大的恐慌传轰,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,607評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件谷婆,死亡現(xiàn)場(chǎng)離奇詭異慨蛙,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)纪挎,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,239評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)期贫,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人异袄,你說(shuō)我怎么就攤上這事通砍。” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,960評(píng)論 0 355
  • 文/不壞的土叔 我叫張陵封孙,是天一觀(guān)的道長(zhǎng)迹冤。 經(jīng)常有香客問(wèn)我,道長(zhǎng)虎忌,這世上最難降的妖魔是什么泡徙? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,750評(píng)論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮膜蠢,結(jié)果婚禮上锋勺,老公的妹妹穿的比我還像新娘。我一直安慰自己狡蝶,他們只是感情好庶橱,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,764評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著贪惹,像睡著了一般苏章。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上奏瞬,一...
    開(kāi)封第一講書(shū)人閱讀 51,604評(píng)論 1 305
  • 那天枫绅,我揣著相機(jī)與錄音,去河邊找鬼硼端。 笑死并淋,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的珍昨。 我是一名探鬼主播县耽,決...
    沈念sama閱讀 40,347評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼镣典!你這毒婦竟也來(lái)了兔毙?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,253評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤兄春,失蹤者是張志新(化名)和其女友劉穎澎剥,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體赶舆,經(jīng)...
    沈念sama閱讀 45,702評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡哑姚,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,893評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了芜茵。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片叙量。...
    茶點(diǎn)故事閱讀 40,015評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖夕晓,靈堂內(nèi)的尸體忽然破棺而出宛乃,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 35,734評(píng)論 5 346
  • 正文 年R本政府宣布征炼,位于F島的核電站析既,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏谆奥。R本人自食惡果不足惜眼坏,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,352評(píng)論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望酸些。 院中可真熱鬧宰译,春花似錦、人聲如沸魄懂。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,934評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)市栗。三九已至缀拭,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間填帽,已是汗流浹背蛛淋。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,052評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留篡腌,地道東北人褐荷。 一個(gè)月前我還...
    沈念sama閱讀 48,216評(píng)論 3 371
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像嘹悼,于是被迫代替她去往敵國(guó)和親叛甫。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,969評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容