请看下面的代码:
function chooseVehicle(option1, option2) {
if(option1 > option2){
return option1 + " is clearly the better choice."
}else if(option1 < option2){
return option2 + " is clearly the better choice."
}
}
console.log(chooseVehicle('Bugatti Veyron', 'Ford Pinto'))
因为字母"B"是在字母"F"我希望输出是这样的,例如:
console.log(chooseVehicle('Bugatti Veyron', 'Ford Pinto'))
"Bugatti Veyron is clearly the better choice."
输出为:
"Ford Pinto is clearly the better choice."
如果有人能帮我解决这个问题,我将不胜感激。
在javascript中不能使用赋值操作符比较字母顺序。而是使用localeCompare()
function chooseVehicle(option1, option2) {
if(option1.localeCompare(option2)){
return option1 + " is clearly the better choice."
}else if(option2.localeCompare(option1)){
return option2 + " is clearly the better choice."
}
}
console.log(chooseVehicle('Bugatti Veyron', 'Ford Pinto'));
或者在比较前先使用.toLowerCase()