适合初学者的 10 个JavaScript 代码整洁技巧

13,006 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第 20 天,点击查看活动详情

什么是整洁的代码呢?答案可能因人而异,个人提倡以函数式风格编写代码,如果做得正确的话,代码将更容易阅读、分解和测试。在开始函数式编程之前,学习一些小的技巧有助于编写整洁的代码。最好的方式是阅读开源项目,学习别人的方式。对于JavaScript,ES6 引入了许多新的特性,也使得写代码多一种更加优雅的方式。

阅读代码,可以站在巨人的肩膀上快速成长的有效方法,GitHub 是程序员学习的首选资源站。

1. 数组合并

// 常规逻辑
const apples = ["🍎", "🍏"];
const fruits = ["🍉", "🍊", "🍇"].concat(apples);

console.log(fruits); // ["🍉", "🍊", "🍇", "🍎", "🍏"];

// 优雅写法 1
const apples = ["🍎", "🍏"];
const fruits = ["🍉", "🍊", "🍇", ...apples];

console.log(fruits); //  ["🍉", "🍊", "🍇", "🍎", "🍏"];

// 优雅写法 2
const apples = ["🍎", "🍏"];
const fruits = [...apples, "🥭", "🍌", "🍒"];
console.log(fruits); // ["🍎", "🍏", "🥭", "🍌", "🍒"];

// 优雅去重
const apples = ["🍎", "🍏", "🍏"];
const fruits = [...new Set(["🍉", "🍊", "🍇", "🍇", ...apples])];
console.log(fruits); // [ '🍉', '🍊', '🍇', '🍎', '🍏' ]

2. 数组中取值

// 常规逻辑
const apples = ["🍎", "🍏"];
const redApple = apples[0];
const greenApple = apples[1];

console.log(redApple); // 🍎
console.log(greenApple); // 🍏;

// 优雅写法
const apples = ["🍎", "🍏"];
const [redApple, greenApple] = apples; // 使用解构赋值

console.log(redApple); // 🍎
console.log(greenApple); // 🍏;

3. 对象取值

// 常规逻辑
const user = {
    name: "DevPoint",
    age: 30,
};

const name = user.name; // DevPoint
const age = user.age; // 30
console.log(name);
console.log(age);

// 优雅写法
const user = {
    name: "DevPoint",
    age: 30,
};

const { name, age } = user;

console.log(name); // DevPoint
console.log(age); // 30

4. 数组循环

数组循环的方法有 .forEach()for...of,在使用上各有特色,但在效率上,for...of 比 .forEach() 快。因此推荐使用 for...of

// 常规逻辑
const fruits = ["🍉", "🍊", "🍇", "🍎"];

for (let i = 0; i < fruits.length; i++) {
    console.log(fruits[i]);
}

// 优雅写法
const fruits = ["🍉", "🍊", "🍇", "🍎"];

for (fruit of fruits) {
    console.log(fruit);
}

5. 箭头函数作为回调

箭头函数是 ES6 中引入新的语法,除了让代码变得优雅的同时,可以避免 this 带来的问题。

// 常规逻辑
const fruits = ["🍉", "🍊", "🍇", "🍎"];

fruits.forEach(function (fruit) {
    console.log(fruit);
});

// 优雅写法
const fruits = ["🍉", "🍊", "🍇", "🍎"];
fruits.forEach((fruit) => console.log(fruit));

6. 数组搜索

数组操作,在前端开发中是比较常见的功能,为了提高开发效率降低重复代码,可以考虑写一个通用的数组操作的脚本库。

假设需要通过一个对象的属性从一个对象数组中查找一个对象,通常使用 for 循环:

// 常规逻辑
const inventory = [
    { name: "Bananas", quantity: 5 },
    { name: "Apples", quantity: 10 },
    { name: "Grapes", quantity: 2 },
];

// Get the object with the name `Apples` inside the array
function getApples(arr, value) {
    for (let index = 0; index < arr.length; index++) {
        if (arr[index].name === "Apples") {
            return arr[index];
        }
    }
}

const result = getApples(inventory);
console.log(result); // { name: 'Apples', quantity: 10 }

// 优雅写法
const inventory = [
    { name: "Bananas", quantity: 5 },
    { name: "Apples", quantity: 10 },
    { name: "Grapes", quantity: 2 },
];

function getApples(arr, value) {
    return arr.find((obj) => obj.name === "Apples");
}

const result = getApples(inventory);
console.log(result);

7.字符串转换为数字

// 常规逻辑
const num = parseInt("10");

console.log(num); // 10
console.log(typeof num); // "number";

// 优雅写法
const num = +"10";
console.log(num); //=> 10
console.log(typeof num); // "number"
console.log(+"10" === 10); // true;

同样的方法可以用于判断是否为整数:

const isInteger = (val) => Number.isInteger(+val);
console.log(isInteger("DevPoint")); // false
console.log(isInteger("30")); // true
console.log(isInteger(30)); // true

8. null 值初始化

// 常规逻辑
function getUserRole(role) {
    let userRole;
    if (role) {
        userRole = role;
    } else {
        userRole = "USER";
    }
    return userRole;
}

console.log(getUserRole()); // "USER"
console.log(getUserRole("ADMIN")); // "ADMIN";

// 优雅写法
function getUserRole(role) {
    return role || "USER"; // 默认值定义的常见方法
}

console.log(getUserRole()); // "USER"
console.log(getUserRole("ADMIN")); // "ADMIN";

9. 字符串拼接

过去无尽的 + 号,再加上一些排版就更痛苦。

// 常规逻辑
const name = "DevPoint";
const message = "Hi " + name + "!";
console.log(message); // Hi DevPoint!
// 优雅写法
const name = "DevPoint";
const message = `Hi ${name}!`;
console.log(message); // Hi DevPoint!

10 对象合并

对象的合并,在ES6中,可以学习一些扩展运算符和解构赋值,这样有利于写出更加简洁的代码。

// 常规逻辑
const employee = { name: "DevPoint", age: 30 };
const salary = { grade: "A" };
const summary = salary;
for (const key in employee) {
    summary[key] = employee[key];
}
console.log(summary); // { grade: 'A', name: 'DevPoint', age: 30 }
// 优雅写法
const employee = { name: "DevPoint", age: 30 };
const salary = { grade: "A" };
const summary = { ...employee, ...salary };
console.log(summary); // { name: 'DevPoint', age: 30, grade: 'A' }