分享篇(如何编写干净的 JavaScript 代码?)

theme: fancy

今天来分享几个编写干净的JavaScript代码的技巧~

1. 更好的命名

在JavaScript中,良好命名的关键不在于最短的变量名,而在于最具描述性的变量名。

(1)减少Magic number

将代码中的一些数字定义为一个常量,以使它更有意义,也便于后期的维护。

for (i=0; i < 8765; i++){}

const HOURS_IN_A_YEAR = 8765

for (i=0; i < HOURS_IN_A_YEAR; i++){}

(2)语义化命名

尽可能语义化变量和函数的名称。

onst expired = true; 
const e = true;
复制代码

const hasExpired = true; // 布尔值应该有一个类似于is、has或was的前缀
const expiredDate = new Date()
let expiredElementsAmount = 0
let allExpiredElemnts = []

2. 保持简洁

(1)避免重复

为了更好地实现简洁的代码,应该遵循DRY(Don't Repeat Yourself)原则。减少代码的重复。


  async function notifyUsers(userIds, message) {
    userIds.foreach(userId => {
      const user = await User.findByPk(userId)
      if(user.isSubscribed) {
        const Notification = await Notifications.create({ 
          date: new Date(),
          user_id: userId,
          message,
          emailNotify: true });   
        Notification.save();
      } else {
        const Notification = await Notifications.create({ 
          date: new Date(),
          user_id: userId,
          message,
          emailNotify: true });   
        Notification.save();
      }
    }
  }

async function notifyUsers(userIds, message) {
    userIds.foreach(userId => {
      const user = await User.findByPk(userId)
      notifyUsers(userId, message, user.isSubscribed)
    }
}
                    
async function createNotification(userId, message, isSubscribed) {
      const Notification = await Notifications.create({ 
          date: new Date(),
          user_id: userId,
          message,
          emailNotify: isSubscribed });   
        Notification.save();
}

(2)使用递归

有些情况下,使用递归的代码会比迭代更加简洁。

const stepsToHundred = (number) => {
  let steps = 0
  
  while(number < 100) {
    number *= 2
    steps++
  }
  
  return steps
}

const stepsToHundred = (number, steps) =>
number < 100 ? stepsToHundred(number * 2, steps + 1) : steps

(3)字符串连接

ES6中新增了模板字符串功能使我们可以在拼接字符串时代码更短、更简洁。

const welcomeMessage = "你好" + user1 + ", 我是" + user2;

const welcomeMessage = `你好 ${user1}, 我是 ${user2}`

3. 减少多层嵌套

(1)条件语句

不要将 return 语句嵌套到 if-else 中。

const getUSTime = (time) => {
  if(time <= 12){
    return time + "AM"
  } else {
    return time + "PM"
  }
}

const getUSTime = (time) => {
  if(time <= 12) return time + "AM"
  return time + "PM"
}

也可以使用三元表达式来写:

const getUSTime = (time) => {
  return time +  (time <= 12 ? "AM" : "PM")
}

(2)async/await

当使用链式的 Promise 时,代码的可读性差就会变差。可以使用async/await来优化异步嵌套的代码。

const sharePost = () => {
  getPost().then(post => {
    sendTweet(post.url, `分享一篇文章: ${post.title}`)
    .then(() => {
      console.log("分享成功");
    });
  });
}

const sharePost = async () => {
  const post = await getPost();
  await sendTweet(post.url, `分享一篇文章: ${post.title}`)
  console.log("分享成功");
}

4. 干净的函数

(1)处理大量参数的函数

当函数的参数很多时,需要按照顺序传递参数就很麻烦,可以使用对象包装所有的参数,这样传递参数时就可以乱序传递,避免传参时出错。

function addUser(firstName, lastName, age, city, state, zipCode) {
    // ... 
}

function addUser({ firstName, lastName, age, city, state, zipCode }) {
    // ...
}

(2)单一责任原则

使用单一职责原则,可以轻松的命名函数,每个函数只做一件事。可以通过它的名称确切地知道该函数的作用,并且该函数不会是冗长的。

async function signupUser(email) {
  const user = await User.create({ email });
  await user.save();
  
  const notifcation = await Notification.create({ email });
  await notifcation.save();
  
  const date = new Date()
  Log.add(date, "已注册", email)
}


const logSignup(email) => Log.add(new Date(), "已注册", email)

async function signupUser(email) {
  createUser(email)
  notifyUser(email)
  logSignup(email)
}

async function createUser(email) {
  const user = await User.create({ email });
  await user.save();
}

async function notifyUser(email) {
  const notifcation = await Notification.create({ email });
  await notifcation.save();
}

(3)回调中首选箭头函数

在JavaScript中,mapfilter等方法都需要一个匿名函数作为参数,在这些情况下,使用箭头函数是最方便和优雅的方式

[1, 2, 3].forEach(function (x) {
  const y = x ** 2;
  return x + y;
});

[1, 2, 3].forEach((x) => {
  const y = x ** 2;
  return x + y;
});

文章源于:如何编写干净的 JavaScript 代码? - 掘金

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值