天天看點

讓JavaScript更簡潔的15個技巧

作者:陸榮濤

簡潔而優雅的代碼總是能讓人賞心悅目,不管你是初入職場的小白還是混迹職場的老鳥。都需要一段簡潔幹淨的代碼,這篇文章就給大家介紹15個讓JavaScript更簡潔的技巧。

01、使用對象解構來獲得更清晰的代碼

// Bad
const firstName = user.firstName;
const lastName = user.lastName;

// Good
const { firstName, lastName } = user;           

02、利用擴充文法進行對象和數組操作

// Bad
const newArray = [...oldArray];

// Good
const newArray = [...oldArray];           

03、避免直接修改函數參數

// 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、在函數參數中使用數組和對象解構

// 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() 進行複雜的數組操作

// 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、對私有資料使用閉包

const counter = (() => {
  let count = 0;
  return {
    increment: () => {
      count++;
    },
    getCount: () => {
      return count;
    },
  };
})();           

12、實施記憶以優化性能

const memoizedFunction = (() => {
  const cache = {};
  return (arg) => {
    if (cache[arg]) {
      return cache[arg];
    }
    const result = expensiveOperation(arg);
    cache[arg] = result;
    return result;
  };
})();           

13、避免改變對象和數組

// Bad
const person = {
  name: 'John',
  age: 30,
};
person.age = 31;

// Good
const person = {
  name: 'John',
  age: 30,
};
const updatedPerson = { ...person, age: 31 };           

14、将複雜的功能分解成更小的、可重用的功能

// 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、遵循單一職責原則 (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}`);           

繼續閱讀