放心寫 JS 三元表達式

本文鼓吹各位 前端 在寫 JS 的時候放心大膽寫三目表達式,
不要人云亦云說「不建議使用三元表達式」。歡迎交流不一樣意見。前端


三元表達式是啥?

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


三元表達式怎麼用?

1. 賦值:
const foo = condition ? 'bar' : 'baz'
2. 執行操做:
condition
    ? (...)
    : (...)
3. 做爲返回值:
function(condition) {
    return condition ? 'bar' : 'baz'
}

三元表達式怎麼就有用了?

代碼量會減小這是事實
配合箭頭函數寫函數式代碼,哪一個更易讀這個就是主觀判斷了,
見仁見智:react

實現一個 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 裏面的一個方法:vim

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

jsx 寫 react 應該很經常使用吧,畢竟沒有 v-if v-else:ide

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

想到再補充函數

缺點?

那些說「我的不推薦三元表達式」的,都是從其餘人那裏聽來的吧?流言止於智者。ui

standard js 說要把問號和冒號放前面:
image.pngspa

airbnb style guide 說,對於多重條件的三元建議分開寫:
image.pngprototype

而谷歌的 js 代碼建議就只說過建議三元表達式記得在 ?: 左右加空格,沒有不推薦三元表達式啊。3d

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

這是你不用三元的緣由?我相信時刻 lint 的你,不會把多重條件寫成 inline 的:

image.png

👆規範使用三元運算符,比 if-else 簡潔。。。吧?

寫了兩年多了,三元的缺點更可能是在配合加號的時候操做順序上:不少人不知道 const a = true ? 1 : 2 + 3 的答案是什麼。而不是在多重 condition 的時候引發 bug。


其實這東西和 vim-emacs,space-tab,2空格-4空格 同樣,就是個風格問題,說「我的不推薦」的是不知道 JS 能夠換行縮進呢?仍是說故意想讓別人喜歡上本身熟悉的風格呢?見仁見智嘛。

相關文章
相關標籤/搜索