元問答欄目視頻美女
  1. 編程問答
  2. 答案列表

怎麼使用 JavaScript 編寫更好的條件語句

回答列表
4.默認參數和解構。
當使用 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
如果 vegetable 是一個對象呢?我們能賦一個默認參數嗎?
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
在上面的例子中,如果vegetable 存在,我們想要列印 vegetable name,否則列印"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 } 解構參數,然後我們就能在代碼中使用 name 作為變量,而不是 vegetable.name
我們還賦了一個空對象 {} 作為默認值,因為當執行 printvegetablename(undefined) 時會得到一個錯誤:不能從 undefined 或 null 解構屬性 name,因為在 undefined 中沒有 name 屬性。
5.用 array.every &array.some 匹配全部/部分內容。
我們能使用數組方法減少代碼行。查看下面的代碼,我們想要檢查是否所有的水果都是紅色的:
const fruits = [。
{ name:'apple',color:'red'}
{ name:'banana',color:'yellow'}
{ name:'grape',color:'purple'}
];
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',color:'red'}
{ name:'banana',color:'yellow'}
{ name:'grape',color:'purple'}
];
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',color:'red'}
{ name:'banana',color:'yellow'}
{ name:'grape',color:'purple'}
];
function test() {
// condition:if any fruit is red
const isanyred = fruits.some(f =>f.color == 'red');
console.log(isanyred);// true
}
6.使用可選鏈和空值合併。
這有兩個為編寫更清晰的條件語句而即將成為 javascript 增強的功能。當寫這篇文章時,它們還沒有被完全支持,你需要使用 babel 來編譯。
可選鏈允許我們沒有明確檢查中間節點是否存在地處理 tree-like 結構,空值合併和可選鏈組合起來工作得很好,以確保為不存在的值賦一個默認值。
這有一個例子:
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 = 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');
}
}
這看起來很美觀並容易維護。它已經到 tc39 stage 3 階段,讓我們等待它獲得批准,然後我們就能無處不在地看到這難以置信的語法的使用。
總結。
讓我們為了編寫更清晰、易維護的代碼,學習並嘗試新的技巧和技術,因為在幾個月後,長長的條件看起來像搬石頭砸自己的腳。
感謝大家的閱讀。
在任何程式語言中,代碼需要根據不同的條件在給定的輸入中做不同的決定和執行相應的動作。
例如,在一個遊戲中,如果玩家生命點為0,遊戲結束。在天氣應用中,如果在早上被查看,顯示一個日出圖片,如果是晚上,則顯示星星和月亮。在這篇文章中,我們將探索javascript中所謂的條件語句如何工作。
如果你使用javascript工作,你將寫很多包含條件調用的代碼。條件調用可能初學很簡單,但是還有比寫一對對if/else更多的東西。這裡有些編寫更好更清晰的條件代碼的有用提示。
數組方法 array.includes提前退出 / 提前返回用對象字面量或map替代switch語句默認參數和解構用 array.every &array.some 匹配全部/部分內容使用可選鏈和空值合併1.數組方法 array.includes
使用 array.includes 進行多條件選擇。
例如:
function printanimals(animal) {
if (animal === 'dog'|| animal === 'cat') {
console.log(i have a ${animal});
}
}
console.log(printanimals('dog'));// i have a dog
上面的代碼看起來很好因為我們只檢查了兩個動物。然而,我們不確定用戶輸入。如果我們要檢查任何其他動物呢?如果我們通過添加更多「或」語句來擴展,代碼將變得難以維護和不清晰。
解決方案:
我們可以通過使用 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
這裡,我們創建來一個動物數組,所以條件語句可以和代碼的其餘部分抽象分離出來。現在,如果我們想要檢查任何其他動物,我們只需要添加一個新的數組項。
我們也能在這個函數作用域外部使用這個動物數組變量來在代碼中的其他任意地方重用它。這是一個編寫更清晰、易理解和維護的代碼的方法,不是嗎?
2.提前退出 / 提前返回。
這是一個精簡你的代碼的非常酷的技巧。我記得當我開始專業工作時,我在第一天學習使用提前退出來編寫條件。
讓我們在之前的例子上添加更多的條件。用包含確定屬性的對象替代簡單字符串的動物。
現在的需求是:
如果沒有動物,拋出一個異常列印動物類型列印動物名字列印動物性別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'
你覺得上面的代碼怎麼樣。
它工作得很好,但是代碼很長並且維護困難。如果不使用lint工具,找出閉合花括號在哪都會浪費很多時間。
猜你喜歡
相關推薦