如何在 javascript 中切换值?例如,如果 x = apple,则函数应返回 x = orange。如果 x = orange,则函数应返回 x = apple。 不确定,这里有什么用,切换或交换。
最佳答案
使用 if/else 子句:
toggleFruit(x) {
if (x === 'apple') {
x = 'orange';
} else {
x = 'apple';
}
return x;
}
或使用三元运算符
toggleFruit(x){
return x = x === 'apple' ? 'orange' : 'apple'
}
关于JavaScript 切换/交换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48916603/