JS簡(jiǎn)寫(xiě)
三元運(yùn)算符
當(dāng)你想寫(xiě)一個(gè)if . .else語(yǔ)句只在一行中。
普通寫(xiě)法
const x = 20;
let answer;
if (x > 10) {
answer = 'is greater';
} else {
answer = 'is lesser';
}
速寫(xiě)
const answer = x > 10 ? 'is greater' : 'is lesser';
你也可以像這樣嵌套if語(yǔ)句:
const big = x > 10 ? " greater 10" : x
短路操作
當(dāng)將變量值賦給另一個(gè)變量時(shí),您可能希望確保源變量不是空的、未定義的或空的。你可以寫(xiě)一個(gè)長(zhǎng)的如果有多個(gè)條件語(yǔ)句,或使用一個(gè)短路操作。關(guān)于操作符可以參考《 告訴你兩個(gè)非常實(shí)用的操作符 》
普通寫(xiě)法
if (variable1 !== null || variable1 !== undefined || variable1 !== '') {
let variable2 = variable1;
}
速寫(xiě)
const variable2 = variable1 || 'new';
變量聲明簡(jiǎn)寫(xiě)
在函數(shù)開(kāi)始時(shí)聲明變量賦值是很好的做法。這種簡(jiǎn)寫(xiě)方法可以在同時(shí)聲明多個(gè)變量時(shí)節(jié)省大量的時(shí)間和空間。
普通寫(xiě)法
let x;
let y;
let z = 3;
速寫(xiě)
let x, y, z=3;
如果存在簡(jiǎn)寫(xiě)
這可能是微不足道的,但值得一提。
普通寫(xiě)法
if (likeJavaScript === true)
速寫(xiě)
if (likeJavaScript)
這是另一個(gè)例子。如果a不等于true,那么就做一些事情。
普通寫(xiě)法
let a;if ( a !== true ) {// do something...}
速寫(xiě)
let a;if ( !a ) {// do something...}