放心写-JS-三元表达式

13次阅读

共计 1663 个字符,预计需要花费 5 分钟才能阅读完成。

本文鼓吹各位 前端 在写 JS 的时候放心大胆写三目表达式,
不要人云亦云说「不建议使用三元表达式」。欢迎交流不同意见。


三元表达式是啥?

RTFM: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator


三元表达式怎么用?

1. 赋值:const foo = condition ? 'bar' : 'baz'
2. 执行操作:condition
    ? (...)
    : (...)
3. 作为返回值:function(condition) {return condition ? 'bar' : 'baz'}

三元表达式怎么就有用了?

代码量会减少这是事实
配合箭头函数写函数式代码,哪个更易读这个就是主观判断了,
见仁见智:

实现一个 flat 函数:const isArr = arg => Object.prototype.toString.call(arg) === '[object Array]'
const flat = inputAny =>
  (isArr(inputAny[0])
      ? flat(inputAny[0])
      : [inputAny[0]]
  )
  .concat(
    inputAny.length > 1
      ? flat(inputAny.slice(1))
      : [])

同样的思路用 if-else:const flat = inputAny => {
  let pre
  if (isArr(inputAny[0]) {pre = flat(inputAny[0])
  } else {pre = [inputAny[0]]
  }
  if (inputAny.length > 1) {return pre.concat(flat(inputAny.slice(1)))
  } else {return pre.concat([])
  }
}
function example() {
    return condition1 ? value1
         : condition2 ? value2
         : condition3 ? value3
         : value4;
}

function example() {if (condition1) {return value1;}
    else if (condition2) {return value2;}
    else if (condition3) {return value3;}
    else {return value4;}
}

vue 里面的一个方法:

根据 data.hide 配合 className 控制元素显隐:<div class="btn" :class="hide ?'_hide':''">
...
btn {translate: ...}
btn._hide {
    opacity: 0;
    transform: ...
}

jsx 写 react 应该很常用吧,毕竟没有 v-if v-else:

export default function () {
  return (<div className={ctnr}>
        condition
            ? <div>yes</div>
            : <div>no</div>    
    </div>
  )
}

想到再补充

缺点?

那些说「个人不推荐三元表达式」的,都是从其他人那里听来的吧?流言止于智者。

standard js 说要把问号和冒号放前面:

airbnb style guide 说,对于多重条件的三元建议分开写:

而谷歌的 js 代码建议就只说过建议三元表达式记得在 ?: 左右加空格,没有不推荐三元表达式啊。

var k = a ? (b ? (c ? d : e) : (d ? e : f)) : f ? (g ? h : i) : j

这是你不用三元的原因?我相信时刻 lint 的你,不会把多重条件写成 inline 的:

???? 规范使用三元运算符,比 if-else 简洁。。。吧?

写了两年多了,三元的缺点更多是在配合加号的时候操作顺序上:很多人不知道 const a = true ? 1 : 2 + 3 的答案是什么。而不是在多重 condition 的时候引起 bug。


其实这东西和 vim-emacs,space-tab,2 空格 - 4 空格 一样,就是个风格问题,说「个人不推荐」的是不知道 JS 可以换行缩进呢?还是说故意想让别人喜欢上自己熟悉的风格呢?见仁见智嘛。

正文完
 0