天天看点

让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}`);           

继续阅读