JavaScript 条件三元运算符的更简洁的替代方案?



在许多情况下,使用conditional ternary operator允许优先选择const而不是let

let scaleFactor = 1;
if (prev.scale < 1 && current.scale < 1) {
scaleFactor = 5;
}

使用三元和常量:

const scaleFactor =
prev.scale < 1 && current.scale < 1 ? 5 : 1;

我经常看到并使用这种模式。有没有更简洁的方式来写我一直缺少的这个?

更新:三元的替代示例,既短又更具可读性

const t =  tX > 0
? 0
: tX < width - width * scale
? width - width * scale
: tX
const t = Math.max(Math.min(tX, 0), width - width * scale)

虽然我完全同意一些人评论你的问题,简短!=简洁,但我确实认为你的问题是有效的。对于许多情况,如果将值设置为 X,则将模式设置为 Y,则可以执行将布尔条件作为因子的表达式。一些选项:

if (C)
value = X
else
value = Y

可以转换为

value = C * X + !C * Y;

同样的事情可以写成:

value = X + !C * (Y - X)

我是一名游戏开发人员,我经常需要这样的东西:

// 1 if the right arrow was pressed, -1 for the left, 0 otherwise
var changeInMovementX = hasRightArrowBeenPressed - hasLeftArrowBeenPressed;
// same for up and down
var changeInMovementY = hasTopArrowBeenPressed - hasDownArrowBeenPressed;
// move 1 pixel in the given directions
player.move(changeInMovementX, changeInMovementX);

对于您的特定示例,您可以考虑如下内容:

const shouldIncreaseScale = prev.scale < 1 && current.scale < 1;
const scaleIncrease = 4;
const scaleFactor = 1 + shouldIncreaseScale * scaleIncrease;

简而言之,像switch表达式这样的语言功能在Javascript中尚不存在。但是您可以根据自己的喜好做一些事情

  1. 带有返回的开关语句的 IIFE
const a = 5
const c1 = (() => {
switch (a) {
case 1: {
return 2
}
case 2: {
return 3
}
default: {
return 4
}
}
})()
console.log(c1)
  1. IIFE with if 语句
const c2 = (() => {
if (a === 1) {
return 2
} else if (a < 10 && b > 10) {
return 3
} else {
return 4
}
})()
console.log(c2)
  1. 自定义帮助程序
// define this once
const conditionalHelper = (cases, defaultValue) => {
for (let i = 0; i < cases.length; i++) {
const [predicate, value] = cases[i]
if (predicate()) {
return value
}
}
return defaultValue
}
const c3 = conditionalHelper(
[
[() => a === 1, 2],
[() => a < 10 && b > 10, 3],
],
4
)
console.log(c3)

最新更新