本文鼓吹各位 前端 在写 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 说要把问号和冒号放前面:spa
airbnb style guide 说,对于多重条件的三元建议分开写:prototype
而谷歌的 js 代码建议就只说过建议三元表达式记得在 ?
和 :
左右加空格,没有不推荐三元表达式啊。3d
这是你不用三元的缘由?我相信时刻 lint 的你,不会把多重条件写成 inline 的:
👆规范使用三元运算符,比 if-else 简洁。。。吧?
写了两年多了,三元的缺点更可能是在配合加号的时候操做顺序上:不少人不知道 const a = true ? 1 : 2 + 3
的答案是什么。而不是在多重 condition 的时候引发 bug。
其实这东西和 vim-emacs,space-tab,2空格-4空格 同样,就是个风格问题,说「我的不推荐」的是不知道 JS 能够换行缩进呢?仍是说故意想让别人喜欢上本身熟悉的风格呢?见仁见智嘛。