4个编写短小精炼JS代码的小技巧(分享)

文章2022-06-2762 人已阅来源:网络

如何让编写的JS代码更短?下面本篇文章就来给大家分享4个编写短小精炼JS代码的小技巧,希望对大家有所帮助!

4个编写短小精炼JS代码的小技巧(分享)

短路

Javascript 里的逻辑运算符与(&&)可以产生短路,例如

console.log(true && 0 && 2); // 0
console.log(true && 'test' && 2) // 2

即代码从左往右,如果遇到undefinednull0等等会被转化为false的值时就不再继续运行。

x == 0 && foo()
// 等价于
if( x == 0 ){
  foo()
}

链判断运算符 '?'

假设有一个对象

const student = {
    name : {
      firstName : 'Joe'
  }
}

我们希望firstname存在的情况下做一些事情, 我们不得不一层一层检查

if(student && student.name && student.name.firstName){
    console.log('student First name exists')
}

采用链判断运算符会在某一层取不到值的时候停止并返回undefined

if(student?.name?.firstName){
    console.log('student First name exists')
}

空值合并运算符 '??'

我们有时候会使用三元运算来简化if...else... 或者返回一个默认值

const foo = () => {
    return student.name?.firstName 
        ? student.name.firstName 
        : 'firstName do not exist'
}
console.log(foo())

这种情况,我们可以通过空值合并进一步简化代码

const foo = () => {
    return student.name?.firstName ?? 'firstName do not exist'
}
console.log(foo())

很像或||运算符,但??只对undefinednull起作用,可以避免值是0麻烦

尽量避免if else 嵌套

例如

const foo = () => {
    if(x<1) {
      return 'x is less than 1'
    } else {
      if(x > 1){
          return 'x is greater than 1'
      } else {
          return 'x is equal to 1'
      }
  }
}

通过删除 else 条件可以使 if else 嵌套变得不那么复杂,因为 return 语句将停止代码执行并返回函数

const foo = () => {
    if(x<1){
        return 'less than 1'
    }
    if(x>1){
        return 'x is greater than 1'
    }
    return 'x is equal to 1'
}

好的代码不一定要追求尽可能的短,有时候过于精简的代码会使debug的过程更加麻烦,所以可读性才是最重要的,特别是在多人协作的情况下。

更多编程相关知识,请访问:编程入门!!

以上就是4个编写短小精炼JS代码的小技巧(分享)的详细内容!