切换 < 或 > 值大小写
Switch < or > value case
我只是想知道是否有办法让这种事情在 switch 语句中起作用,我知道这在 else if 语句中很有可能,但我更愿意使用 switch 语句,下面我附上了一段示例代码来说明我的意思...
let money = 42;
switch (money) {
case < 10:
console.log('You have or less USD');
break;
case < 50:
console.log('You have or less USD');
break;
case < 100:
console.log('You have 0 or less USD');
break;
default:
console.log('You are rich! Over 0);
break;
}
如果这按照我想要的方式工作,它会打印“你有 50 美元或更少美元”,因为钱 < 50 但 > 10。
提前致谢,Lachie。
实际上有一个很好的方法可以做到这一点,请注意 switch(true)
将计算每个表达式。
并不总是可读的,但很高兴知道。
const money = 200;
switch (true) {
case money < 10:
console.log('You have or less USD');
break;
case money < 50:
console.log('You have or less USD');
break;
case money < 100:
console.log('You have 0 or less USD');
break;
default:
console.log('You are rich! Over 0');
break;
}
const run = (money) => {
switch (true) {
case money < 10:
console.log('You have or less USD');
break;
case money < 50:
console.log('You have or less USD');
break;
case money < 100:
console.log('You have 0 or less USD');
break;
default:
console.log('You are rich! Over 0');
break;
}
};
run(42);
run(55);
run(123);
你需要用你手上的钱做个比较
我只是想知道是否有办法让这种事情在 switch 语句中起作用,我知道这在 else if 语句中很有可能,但我更愿意使用 switch 语句,下面我附上了一段示例代码来说明我的意思...
let money = 42;
switch (money) {
case < 10:
console.log('You have or less USD');
break;
case < 50:
console.log('You have or less USD');
break;
case < 100:
console.log('You have 0 or less USD');
break;
default:
console.log('You are rich! Over 0);
break;
}
如果这按照我想要的方式工作,它会打印“你有 50 美元或更少美元”,因为钱 < 50 但 > 10。
提前致谢,Lachie。
实际上有一个很好的方法可以做到这一点,请注意 switch(true)
将计算每个表达式。
并不总是可读的,但很高兴知道。
const money = 200;
switch (true) {
case money < 10:
console.log('You have or less USD');
break;
case money < 50:
console.log('You have or less USD');
break;
case money < 100:
console.log('You have 0 or less USD');
break;
default:
console.log('You are rich! Over 0');
break;
}
const run = (money) => {
switch (true) {
case money < 10:
console.log('You have or less USD');
break;
case money < 50:
console.log('You have or less USD');
break;
case money < 100:
console.log('You have 0 or less USD');
break;
default:
console.log('You are rich! Over 0');
break;
}
};
run(42);
run(55);
run(123);
你需要用你手上的钱做个比较