【发布时间】:2019-01-26 20:12:43
【问题描述】:
大多数情况下,我们使用 If else 语句并编写其语法糖等价物很容易。
If(condition){trueExecute}else{falseExecute}
它的语法糖是
condition?trueExecute:falseExecute
但我在下面的代码中遇到问题,因为我不想使用 else。最重要的是,我想在循环中使用 break 或 continue 函数。当我使用正常的 If 语句时;代码是完美的。但是每当我尝试使用语法糖来替换 if 时,它都无法执行。
是否有可能的解决方案,因为我找到的所有示例都没有解决这个问题
我的代码:
const NUMBER = 5346789123;
let anotherNew = NUMBER.toString();
let stringNumber = "";
let newString = anotherNew.length;
for(let numCount = 0; numCount < newString; numCount++){
if (anotherNew[numCount] == 4){
console.log('we have removed 4');
continue;
}
if (anotherNew[numCount] == 9){
console.log('we have a break');
break;
}
stringNumber += anotherNew[numCount];
console.log(stringNumber);
}
我试图用语法糖来替换 if 语句,但它会导致错误
anotherNew[numCount] == 4? console.log('we have removed 4') continue;
anotherNew[numCount] == 9? console.log('we have a break') break;
【问题讨论】:
-
条件运算符是
if/else的not 语法糖。条件运算符的计算结果为 表达式,而if/else执行 语句。它们适用于不同的事物。最好不要为了节省几个字符而滥用条件运算符,你会混淆你的代码的读者。
标签: javascript ecmascript-6 syntactic-sugar