tft每日頭條

 > 圖文

 > 前端開發之if-else 的優化過程

前端開發之if-else 的優化過程

圖文 更新时间:2024-10-11 03:14:53

前端開發之if-else 的優化過程?編寫 if-else 是程序員的日常工作 每當我們編寫代碼時,我們都會檢查某事是真還是假 但是編寫太多 if-else 條件會使代碼不可讀 以下是我重構 if-else 塊時遵循的一些步驟,下面我們就來聊聊關于前端開發之if-else 的優化過程?接下來我們就一起去了解一下吧!

前端開發之if-else 的優化過程(七爪源碼如何重構)1

前端開發之if-else 的優化過程

編寫 if-else 是程序員的日常工作。 每當我們編寫代碼時,我們都會檢查某事是真還是假。 但是編寫太多 if-else 條件會使代碼不可讀。 以下是我重構 if-else 塊時遵循的一些步驟。

方法調用:

有時基于一個參數,我們不得不做不同的操作。

class SomeClass { public action(status: string) { if (status === ‘draft’) { //Do some operations } else if (status === ‘confirmed’) { //Do some operations } else if (status === ‘payed’) { //Do some operations } else if (status === ‘shipped’) { //Do some operations } } }

我們可以通過根據參數值調用方法來改善這一點。

class SomeClass { public action(status: string) { if (typeof this[status] === ‘undefined’) { //Throw your exception, do some default operations and return } return this[status]() } public draft() { //Do the draft operations } public confirmed() { //Do the confirm operations } public payed() { //Do the payed operations } public shipped() { //Do shipped operations } }

對象字面量:

如果您隻需要基于參數返回一個值,那麼您可以使用對象字面量

if (operator === ‘=’) { return a === b; } else if (operator === ‘<’) { return a < b; } else if (operator === ‘>’) { return a > b; } else if (operator === ‘>=’) { return a >= b; } else if (operator === ‘<=’) { return a <= b; } else if (operator === ‘like’) { return String(a).toLowerCase().includes(String(b).toLowerCase()); }

重構

action(operator) { const operators = { ‘=’: (a, b) => a === b, ‘<’: (a, b) => a < b, ‘>’: (a, b) => a > b, ‘>=’: (a, b) => a >= b, ‘<=’: (a, b) => a <= b, like: (a, b) => String(a).toLowerCase().includes(String(b).toLowerCase()), }; if (typeof operators[operator] === ‘undefined’) { //Do your operation and return } return operators[operator]; }

注意:我們也可以使用工廠設計模式。 但在大多數情況下,這将是矯枉過正

對于更多這樣的内容。 請務必關注我。

更多精彩资讯请关注tft每日頭條,我们将持续为您更新最新资讯!

查看全部

相关圖文资讯推荐

热门圖文资讯推荐

网友关注

Copyright 2023-2024 - www.tftnews.com All Rights Reserved