淺談JS如何寫出漂亮的條件表示式
多條件語句
多條件語句使用Array.includes
舉個例子
function printAnimals(animal) {
if (animal === "dog" || animal === "cat") {
console.log(`I have a ${animal}`);
}
}
www.cppcns.com
console.log(printAnimals("dog")); // I have a dog
這種寫法在條件比較少的情況下看起來沒有問題,此時我們只有 2 種動物,但是如果我們有更多的條件需要判斷(更多的動物)呢?如果我們繼續拓展判斷的條件,那麼程式碼將會變得難以維護,而且邏輯會不清晰。
解決方法
可以使用Array.includes來重寫條件語句
function printAnimals(animal) {
const animals = ["dog","cat","hamster","turtle"];
if (animals.includes(animal))程式設計客棧 {
console.log(`I have a ${animal}`);
}
}
console.log(printAnimals("hamster")); // I have a hamster
在這裡,我們建立了一個動物陣列,以便將條件與程式碼的其餘部分分開提取。現在,如果我們想要檢查任何其他動物,我們需要做的就是新增一個新的陣列項。
我們還可以在這個函式的範圍之外使用 animals 變數,以便在程式碼的其他地方重用它。這是一種編寫更清晰、更容易理解和維護的程式碼的方法。不是嗎?
多屬性物件
這是一個非常好的技巧來壓縮你的程式碼,使它看起來更簡潔。讓我們以前面的示例為例,新增更多的條件。如果這個動物不是一個簡單的字串,而是一個具有某些屬性的物件呢?
所以現在的要求是:
- 如果沒有動物,丟擲一個錯誤
- 列印動物的型別
- 列印動物的名字
- 列印動物的性別
const printAnimalDetails = (animal) => { let result; // declare a variable to store the final value // condition 1: check if animal has a value if (animal) { // condition 2: check if animal has a type property if (animal.type) { // condition 3: check if animal has a name property if (animal.name) { // condition 4: check if animal has a gender property if (animal.gender) { result = `${animal.name} is a ${animal.gender} ${animal.type};`; } else { result = "No animal gender"; } } else { result = "No animal name"; } } else { result = "No animal type"; } } else { result = "No animal"; } return result; }; console.log(printAnimalDetails()); // 'No animal' console.log(printAnimalDetails({ type: "dog",gender: "female" })); // 'No animal name' console.log(printAnimalDetails({ type: "dog",name: "Lucy" })); // 'No animal gender' console.log( printAnimalDetails({ type: "dog",name: "Lucy",gender: "female" }) ); // 'Lucy is a female dog'
上面的程式碼它工作得很好,但是程式碼很長,很難維護。如果不使用提示工具,可能會浪費一些時間來確定右括號的位置。想象將會發生什麼如果程式碼更復雜的邏輯。很多if...else的語句!
我們可以使用三元操作符、&&條件等來重構上面的函式,但是讓我們使用多個返回語句來編寫更精確的程式碼。
const printAnimalDetails = ({ type,name,gender } = {}) => { if (!type) return "No animal type"; if (!name) return "No animal name"; if (!gender) return "No animal gender"; // Now in this line of code,we're sure that we have an animal with all //the three properties here. return `${name} is a ${gender} ${type}`; }; console.log(printAnimalDetails()); // 'No animal type' console.log(printAnimalDetails({ type: dog })); // 'No animal name' console.log(printAnimalDetails({ type: dog,gender: female })); // 'No animal name' console.log(printAnimalDetails({ type: dog,gender: "female" })); // 'Lucy is a female dog'
在重構版本中,還包括解構和預設引數。預設引數確保如果我們將 undefined 作為引數傳遞給方法,我們仍然有一個要解構的值,這裡是一個空物件 {}。
通常,程式碼是在這兩種方法之間編寫的。
舉個例子
function printVegetablesWithQuantity(vegetable,quantity) { const vegetables = ["potato","cabbage","cauliflower","asparagus"]; // condition 1: vegetable should be present if (vegetable) { // condition 2: must be one of the item from the list if (vegetables.includes(vegetable)) { console.log(`I like ${vegetable}`); // condition 3: must be large quantity if (quantity >= 10) { console.log("I have bought a large quantity"); } } } else { throw new Error("No vegetable from the list!"); } } printVegetablesWithQuantity(null); // No vegetable from the list! printVegetablesWithQuantity("cabbage"); // I like cabbage printVegetablesWithQuantity("cabbage",20); // 'I like cabbage` // 'I have bought a large quantity'
現在,我們有:
- 過濾無效條件的 if/else 語句
- 3 層巢狀的 if 語句(條件 1、2 和 3)
- 一個通用的規則是當發現無效條件時儘早返回。
function printVegetablesWithQuantity(vegetable,"asparagus"]; // condition 1: throw error early if (!vegetable) throw new Error("No vegetable from the list!"); // condition 2: must be in the list if (vegetables.includes(vegetable)) { console.log(`I like ${vegetable}`); // condition 3: must be a large quantity if (quantity >= 10) { console.log("I have bought a large quantity"); } } }
通過這樣做,我們減少了一個巢狀語句的級別。這種編碼風格很好,特別是當使用長if語句時。通過反轉條件並提前返回,我們可以進一步減少巢狀if。
請看下面的條件 2 是怎麼做的:
function printVegetablesWithQuantity(vegetable,"asparagus"]; if (!vegetable) throw new Error("No vegetable from the list!"); // condition 1: throw error early if (!vegetables.includes(vegetable)) return; // condition 2: return from the function is the vegetable is not in // the list console.log(`I like ${vegetable}`); // condition 3: must be a large quantity if (quantity >= 10) { console.log("I have bought a large quantity"); } }
通過反轉條件 2 的條件,程式碼不再具有巢狀語句。當我們有很多條件並且希望在任何特定條件不滿足時停止進一步的處理時,這種技術是有用的。
因此,總是以減少巢狀和儘早返回為目標,但不要過度。
替換Switch語句
讓我們看一下下面的例子,我們想要根據顏色列印水果:
function printFruits(color) { // use switch case to find fruits by color switch (color) { case "red": return ["apple","strawberry"]; case "yellow": return ["banana","pineapple"]; case "purple": return ["grape","plum"]; default: return []; } } printFruits(null); // [] printFruits("yellow"); // ['banana','pineapple']
上面的程式碼實現沒有錯誤,但是很冗長,同樣的結果可以使用更簡潔的語法來實現。
// use object literal to find fruits by color const fruitColor = { red: ["apple","strawberry"],yellow: ["banana","pineapple"],purple: ["grape","plum"],}; function printFruits(color) { return fruitColor[color] || []; }
同樣的,也可以使用 Map 來實現:
// use Map to find fruits by color const fruitColor = new Map() .set("red",["apple","strawberry"]) .set("yellow",["banana","pineapple"]) .set("purple",["grape","plum"]); function printFruits(color) { return fruitColor.get(color) || []; }
Map是 ES5 以來可用的物件型別,它允許存 key-value。
對於上面的示例,可以使用 Array.filter 實現相同的結果。
const fruits = [ { name: "apple",color: "red" },{ name: "strawberry",{ name: "banana",color: "yellow" },{ name: "pineapple",{ name: "grape",color: "purple" },{ name: "plum",]; function printFruits(color) { return fruits.filter((fruit) => fruit.color === color); }
預設引數與解構
在使用 javascript 時,我們總是需要檢查 null/undefined 並分配預設值或編譯中斷。
function printVegetablesWithQuantity(vegetable,quantity = 1) { // if quantity has no value,assign 1 if (!vegetable) return; console.log(`We have ${quantity} ${vegetable}!`); } //results } printVegetablesWithQuantity('cabbage'); // We have 1 cabbage! printVegetablesWithQuantity('potato',2); // We have 2 potato!
如果蔬菜是一個物件呢?我們可以分配一個預設引數嗎?
function printVegetableName(vegetable) { if (vegetable && vegetable.name) { console.log(vegetable.name); } else { console.log("unknown"); } } printVegetableName(undefined); // unknown printVegetableName({}); // unknown printVegetableName({ name: "cabbage",quantity: 2 }); // cabbage
在上面的示例中,我們希望列印蔬菜名(如果它可用)或列印 unknown。
我們可以通過使用預設引數&解構來避免條件if (vegetable && vegetable.name){}。
// destructing - get name property only // assign default empty object {} function printVegetableName({ name } = {}) { console.log(name || "unknown"); } printVegetableName(undefined); // unknown printVegetableName({}); // unknown printVegetableName({ name: "cabbage",quantity: 2 }); // cabbage
因為我們只需要屬性名,所以我們可以使用 {name} 來改變引數的結構,然後我們可以在程式碼中使用 name 作為變數,而不是使用 vegetable.name。
我們還將一個空物件 {} 賦值為預設值,否則在執行 printVegetableName(undefined) 時,它將給出一個錯誤—— Cannot destructure property name of undefined or null,因為在 undefined 中沒有 name 屬性。
匹配所有或部分條件
我們可以通過使用這些Array方法來減少程式碼行數。
下面的程式碼,我們想要檢查是否所有的水果都是紅色的:
const fruits = [ { name: "apple",]; function test() { let isAllRed = true; // condition: all fruits must be red for (let f of fruits) { if (!isAllRed) break; isAllRed = f.color == "red"; } console.log(isAllRed); // false }
上面的程式碼太過冗長,我們可以通過使用 Array.every 來減少程式碼行:
const fruits = [ { name: "apple",]; function test() { // condition: short way,all fruits must be red const isAllRed = fruits.every((f) => f.color == "red"); console.log(isAllRed); // false }
同樣的,如果我們想要測試任何一個水果是否是紅色的,我們可以使用 Array.some:
const fruits = [ { name: "apple",]; function test() { // condition: if any fruit is red const isAnyRed = fruits.some((f) => f.color == "red"); console.log(isAnyRed); // true }
使用可選鏈和 Nullish 合併
https://developer.mozilla.org/zh-CN/docs/Web/javaScript/Reference/Operators/%E5%8F%AF%E9%80%89%E9%93%BE
這兩個功能對於 JavaScript 編寫更簡潔的條件非常有用。在編寫本文時,它們還沒有得到完全的支援,可能需要使用Babel進行編譯。
程式設計客棧可選連結能夠處理類似樹的結構,而不需要顯式地檢查中間節點是否存在,並且Nullish與可選連結結合使用非常有效,可以確保不存在節點的預設值。
舉個例子:
const car = { model: "Fiesta",manufacturer程式設計客棧: { name: "Ford",address: { street: "Some Street Name",number: "5555",state: "USA",},}; // to get the car model const model = (car && car.model) || "default model"; // to get the manufacturer street const street = (car && car.manufacturer && car.manufacturer.address && car.manufacturer.address.street) || "default street"; // request an un-existing property const phoneNumber = car && car.manufacturer && car.manufacturer.address && car.manufacturer.phoneNumber; console.log(model); // 'Fiesta' console.log(street); // 'Some Street Name' console.log(phoneNumber); // undefined
因此,如果我們想打印出來,如果汽車製造商來自美國,程式碼應該是這樣的:
const isManufacturerFromUSA = () => { if ( car && car.manufacturer && car.manufacturer.address && car.manufacturer.address.state === "USA" ) { console.log("true"); } }; checkCarManufacturerState(); // 'true'
可以清楚地看到,對於更復雜的物件結構,這會變得多麼混亂。有一些第三方庫,如 lodash 或idx,它們有自己的功能。例如 lodash 有 _.get 方法。但是,在 JavaScript 語言本身中引入這個特性。
以下是這些新功能的工作原理:
// to get the car model
const model =PiIZaDJmHV car?.model ?? "default model";
// to get the manufacturer street
const street = car?.manufacturer?.address?.street ?? "default street";
// to check if the car manufacturer is from the USA
const isManufacturerFromUSA = () => {
if (car?.manufacturer?.address?.state === "USA") {
console.log("true");
}
};
目前在 Stage 3 階段。
以上就是基於JavaScript實現條件表示式的一些分享,希望對你能有所幫助~
以上就是淺談js如何寫出漂亮的條件表示式的詳細內容,更多關於JS如何寫出漂亮的條件表示式的資料請關注我們其它相關文章!