在 JavaScript 開發(fā)中,傳統(tǒng)switch
語句存在冗長、易出錯(cuò)、難維護(hù)等弊端。現(xiàn)代 JavaScript 提供了對象映射、Map 數(shù)據(jù)結(jié)構(gòu)等替代方案,能大幅簡化條件邏輯。同時(shí),結(jié)合變量聲明優(yōu)化、箭頭函數(shù)、異步編程改進(jìn)等技巧,可讓代碼更簡潔高效,顯著提升開發(fā)效率與代碼質(zhì)量 。
傳統(tǒng) switch 語句的問題
傳統(tǒng) switch 語句存在冗長、易出錯(cuò)、難維護(hù)和可讀性差等問題,下面是一個(gè)傳統(tǒng) switch 語句的示例:
function getDayName(day) {
switch (day) {
case 1:
return 'Monday';
case 2:
return 'Tuesday';
case 3:
return 'Wednesday';
case 4:
return 'Thursday';
case 5:
return 'Friday';
case 6:
return 'Saturday';
case 7:
return 'Sunday';
default:
return 'Invalid day';
}
}
console.log(getDayName(2));
使用對象替代 switch
對象映射是替代簡單 switch 語句的有效方式,它更簡潔:
function getDayName(day) {
const dayMap = {
1: 'Monday',
2: 'Tuesday',
3: 'Wednesday',
4: 'Thursday',
5: 'Friday',
6: 'Saturday',
7: 'Sunday'
};
return dayMap[day] || 'Invalid day';
}
console.log(getDayName(2));
處理復(fù)雜邏輯
當(dāng)每個(gè)分支包含復(fù)雜邏輯時(shí),可把函數(shù)作為對象的值:
function performAction(action) {
const actions = {
add: (a, b) => a + b,
subtract: (a, b) => a - b,
multiply: (a, b) => a * b,
divide: (a, b) => a / b
};
const actionFn = actions[action];
if (!actionFn) {
return 'Invalid action';
}
return actionFn(10, 5);
}
console.log(performAction('add'));
使用 Map 數(shù)據(jù)結(jié)構(gòu)
ES6 的 Map 數(shù)據(jù)結(jié)構(gòu)比對象字面量功能更強(qiáng)大,適合鍵不限于字符串等場景:
function getDayName(day) {
const dayMap = new Map([
[1, 'Monday'],
[2, 'Tuesday'],
[3, 'Wednesday'],
[4, 'Thursday'],
[5, 'Friday'],
[6, 'Saturday'],
[7, 'Sunday']
]);
return dayMap.get(day) || 'Invalid day';
}
console.log(getDayName(2));
函數(shù)映射和鏈?zhǔn)讲僮?/span>
Map 適合實(shí)現(xiàn)命令模式或策略模式,示例如下:
class Calculator {
constructor() {
this.operations = new Map([
['+', (a, b) => a + b],
['-', (a, b) => a - b],
['*', (a, b) => a * b],
['/', (a, b) => a / b],
['%', (a, b) => a % b]
]);
}
calculate(a, operator, b) {
const operation = this.operations.get(operator);
if (!operation) {
throw new Error(`Unsupported operator: ${operator}`);
}
return operation(a, b);
}
addOperation(operator, fn) {
this.operations.set(operator, fn);
return this;
}
}
const calc = new Calculator()
.addOperation('log', (a, b) => Math.log(a) / Math.log(b));
console.log(calc.calculate(10, '+', 5));
console.log(calc.calculate(10, 'log', 10));
通過運(yùn)用對象映射和 Map 數(shù)據(jù)結(jié)構(gòu),能讓 JavaScript 代碼更簡潔、優(yōu)雅且易于維護(hù)。
還有哪些代碼優(yōu)化技巧?
變量聲明與作用域
使用 const 和 let 替代 var:const 和 let 具有塊級作用域,能避免變量提升帶來的問題,增強(qiáng)代碼的可預(yù)測性。
function testVar() {
if (true) {
var x = 10;
}
console.log(x);
}
function testLet() {
if (true) {
let y = 10;
}
}
減少全局變量的使用:全局變量易引發(fā)命名沖突和代碼難以維護(hù),盡量將變量的作用域限制在函數(shù)或模塊內(nèi)部。
函數(shù)優(yōu)化
箭頭函數(shù):它是一種更簡潔的函數(shù)定義方式,特別適合簡單的回調(diào)函數(shù),并且它沒有自己的 this、arguments、super 或 new.target,this 值繼承自外層函數(shù)。
const numbers = [1, 2, 3];
const squared = numbers.map(function(num) {
return num * num;
});
const squaredWithArrow = numbers.map(num => num * num);
函數(shù)柯里化:把多參數(shù)函數(shù)轉(zhuǎn)換為一系列單參數(shù)函數(shù),可提高函數(shù)的復(fù)用性。
function add(a, b) {
return a + b;
}
function curriedAdd(a) {
return function(b) {
return a + b;
};
}
const add5 = curriedAdd(5);
console.log(add5(3));
循環(huán)優(yōu)化
避免在循環(huán)中重復(fù)計(jì)算:如果循環(huán)條件或循環(huán)體中有重復(fù)計(jì)算的部分,應(yīng)提前計(jì)算好。
const arr = [1, 2, 3, 4, 5];
for (let i = 0; i < arr.length; i++) {
}
const len = arr.length;
for (let i = 0; i < len; i++) {
}
使用 for...of 或數(shù)組方法替代傳統(tǒng) for 循環(huán):for...of 語法更簡潔,數(shù)組方法(如 map、filter、reduce 等)能讓代碼更具聲明性。
const numbers = [1, 2, 3];
for (const num of numbers) {
console.log(num);
}
numbers.forEach(num => console.log(num));
條件判斷優(yōu)化
三元運(yùn)算符:對于簡單的條件判斷,使用三元運(yùn)算符可以讓代碼更簡潔。
let result;
if (x > 10) {
result = 'Greater than 10';
} else {
result = 'Less than or equal to 10';
}
const resultWithTernary = x > 10 ? 'Greater than 10' : 'Less than or equal to 10';
邏輯與(&&)和邏輯或(||)短路求值:可以簡化條件判斷和賦值操作。
const name = user.name || 'Guest';
const isAdmin = true;
isAdmin && showAdminPanel();
異步編程優(yōu)化
使用 async/await 替代回調(diào)地獄:async/await 讓異步代碼看起來更像同步代碼,提高了代碼的可讀性和可維護(hù)性。
function getData(callback) {
setTimeout(() => {
const data = { message: 'Hello' };
callback(data);
}, 1000);
}
getData(data => {
console.log(data.message);
});
function getData() {
return new Promise(resolve => {
setTimeout(() => {
const data = { message: 'Hello' };
resolve(data);
}, 1000);
});
}
async function main() {
const data = await getData();
console.log(data.message);
}
main();
性能優(yōu)化
防抖和節(jié)流:在處理高頻事件(如 resize、scroll、input 等)時(shí),使用防抖和節(jié)流可以減少不必要的函數(shù)調(diào)用,提高性能。
function debounce(func, delay) {
let timer;
return function() {
const context = this;
const args = arguments;
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(context, args);
}, delay);
};
}
function throttle(func, limit) {
let inThrottle;
return function() {
const context = this;
const args = arguments;
if (!inThrottle) {
func.apply(context, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
——The End——
該文章在 2025/4/30 17:59:07 編輯過