如何处理条件运算符w JavaScript+;反应
我有以下JavaScript:如何处理条件运算符w JavaScript+;反应,javascript,reactjs,operators,ternary-operator,Javascript,Reactjs,Operators,Ternary Operator,我有以下JavaScript: const { inverseDirection } = this.props; 如果反转为false,我需要以下内容: const dashOffset = dashArray - (dashArray * this.state.percentProgress) / 100; const dashOffset = dashArray + (dashArray * this.state.percentProgress) / 100; 如果反转为真,我
const { inverseDirection } = this.props;
如果反转为false,我需要以下内容:
const dashOffset =
dashArray - (dashArray * this.state.percentProgress) / 100;
const dashOffset =
dashArray + (dashArray * this.state.percentProgress) / 100;
如果反转为真,我需要以下信息:
const dashOffset =
dashArray - (dashArray * this.state.percentProgress) / 100;
const dashOffset =
dashArray + (dashArray * this.state.percentProgress) / 100;
怎样才能在不复制整行内容的情况下优雅地编写代码?您可以这样做
const dashOffset = inverseDirection
? ( dashArray + (dashArray * this.state.percentProgress) / 100)
: (dashArray - (dashArray * this.state.percentProgress) / 100)
不是很优雅,但任何更复杂的东西都是浪费时间,可能不太可读。您可以尝试以下方法:
const { inverse } = this.props;
let calc = (x, y) => (x * y) / 100
let offset = arr + (inverse ? -1 : 1)*(calc(arr, this.state.percentProgress))
通过这种方式,您可以提取/重用calc
函数(或移动到utils
等),而inverse
操作可以归结为简单的inverse-1:1
这才是你真正想要的