语法糖 JavaScript ( If 语句) 错误

Syntactic sugar JavaScript ( If statement) Error

大多数时候我们使用 If else 语句并编写其等效的语法糖很容易。

If(condition){trueExecute}else{falseExecute}

它的语法糖是

condition?trueExecute:falseExecute

但是我在下面的代码中遇到了问题,因为我不想使用 else。最重要的是,我想 在循环中使用 break 或 continue 函数。当我使用普通的 If 语句时;代码是完美的。但是每当我尝试使用语法糖来替换 if 时,它都无法执行。

是否有可能解决这个问题,因为我找到的所有示例,none 都解决了这个问题

我的代码:

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;
anotherNew[numCount] == 4? console.log('we have removed 4') continue;

anotherNew[numCount] == 9? console.log('we have a break') break;

这不仅仅是语法糖。它是三元运算符或条件语句。它不能总是替换代码中的 if else 块。

三元运算符执行语句并根据它们的计算结果为 truefalse 给出输出,而在 if/else 块中我们可以给出我们想要的任何条件。这是个很大的差异。你不能盲目地用一个代替另一个。使用它们时必须牢记某些规则。

I try to use syntactic sugar

The conditional operator 不是 语法糖 。它是具有特定目的的特定运算符,而您只是错误地使用了它。它用于有条件地产生一个值作为一个整体表达式,如果条件为真则产生一个值,如果条件为假则产生另一个值。

例如:

let x = input == 'one' ? 1 : 0;

此表达式根据条件生成整数值。

您要做的只是在条件为真时执行一段代码。而且您已经有了用于此目的的工具,一个 if 语句:

if (anotherNew[numCount] == 4){
    console.log('we have removed 4');
    continue;
}

这里的总体教训是不要试图让您的代码太聪明。您使用 if 语句是为了准确和正确的目的。代码简单明了,随便看一眼就明白了。这些都是好事。不要用简洁复杂的代码替换它们,这些代码以不直观的方式使用工具,只是为了节省几次击键。