15個幫助你寫出更簡潔JavaScript的技巧
作者:web前端開發(fā)
在本文中,我們將分享一些可以幫助你編寫干凈的 JavaScript 代碼的技巧。無論你是初級職位還是高級職位,它都一定會幫助你提高實踐水平。
在本文中,我們將分享一些可以幫助你編寫干凈的 JavaScript 代碼的技巧。無論你是初級職位還是高級職位,它都一定會幫助你提高實踐水平。
01、使用對象解構(gòu)來獲得更清晰的代碼
// Bad
const firstName = user.firstName;
const lastName = user.lastName;
// Good
const { firstName, lastName } = user;
02、利用擴展語法進行對象和數(shù)組操作
// Bad
const newArray = [...oldArray];
// Good
const newArray = [...oldArray];
03、避免直接修改函數(shù)參數(shù)
// Bad
function updateArray(arr) {
arr.push(4);
}
// Good
function updateArray(arr) {
const newArr = [...arr, 4];
return newArr;
}
04、使用模板文字進行字符串插值
// Bad
const fullName = firstName + ' ' + lastName;
// Good
const fullName = `${firstName} ${lastName}`;
05、盡可能使用 const 而不是 let
// Bad
let counter = 0;
// Good
const counter = 0;
06、在函數(shù)參數(shù)中使用數(shù)組和對象解構(gòu)
// Bad
function getUserInfo(user) {
const name = user.name;
const age = user.age;
}
// Good
function getUserInfo({ name, age }) {
// Code to use name and age
}
07、避免深度嵌套代碼和過度縮進
// Bad
if (condition1) {
if (condition2) {
if (condition3) {
// Code
}
}
}
// Good
if (condition1 && condition2 && condition3) {
// Code
}
08、使用 Array.prototype.reduce() 進行復(fù)雜的數(shù)組操作
// Bad
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
// Good
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
09、使用提前返回和保護子句避免不必要的嵌套
// Bad
function calculateTotal(price, quantity) {
if (price && quantity) {
// Code to calculate total
return total;
}
}
// Good
function calculateTotal(price, quantity) {
if (!price || !quantity) {
return;
}
// Code to calculate total
return total;
}
10、用有意義的注釋和 JSDoc 注釋記錄你的代碼
// Bad
// Increment the counter by 1
counter++;
// Good
/**
* Increments the counter by 1.
*/
counter++;
11、對私有數(shù)據(jù)使用閉包
const counter = (() => {
let count = 0;
return {
increment: () => {
count++;
},
getCount: () => {
return count;
},
};
})();
12、實施記憶以優(yōu)化性能
const memoizedFunction = (() => {
const cache = {};
return (arg) => {
if (cache[arg]) {
return cache[arg];
}
const result = expensiveOperation(arg);
cache[arg] = result;
return result;
};
})();
13、避免改變對象和數(shù)組
// Bad
const person = {
name: 'John',
age: 30,
};
person.age = 31;
// Good
const person = {
name: 'John',
age: 30,
};
const updatedPerson = { ...person, age: 31 };
14、將復(fù)雜的功能分解成更小的、可重用的功能
// Bad
function processUserData(userData) {
// complex logic...
}
// Good
function validateUserData(userData) {
// validation logic...
}
function sanitizeUserData(userData) {
// sanitization logic...
}
function processUserData(userData) {
validateUserData(userData);
sanitizeUserData(userData);
// remaining logic...
}
15、遵循單一職責(zé)原則 (SRP)
// Bad
function calculateAreaAndPerimeter(radius) {
const area = Math.PI * radius * radius;
const perimeter = 2 * Math.PI * radius;
console.log(`Area: ${area}, Perimeter: ${perimeter}`);
}
// Good
function cal
culateArea(radius) {
return Math.PI * radius * radius;
}
function calculatePerimeter(radius) {
return 2 * Math.PI * radius;
}
const area = calculateArea(5);
const perimeter = calculatePerimeter(5);
console.log(`Area: ${area}, Perimeter: ${perimeter}`);
總結(jié)
以上就是我今天與你分享的15個關(guān)于寫出更好JS的小技巧,希望對你有用。
責(zé)任編輯:華軒
來源:
今日頭條