"修改汽车绘画示例,以便在您拥有自己喜欢的颜色的情况下为汽车涂上颜色;否则它是用你车库的颜色绘制的(如果颜色已知);否则它被涂成红色。" 汽车绘画示例: car.color = favoriteColor || "黑色&#34 ;;
如何或如何才能使我的脚本有效?
car.color = favoriteColor || "red";
if (car.color = favoriteColor ){
alert("your car is " + favoriteColor);
} else if (car.color = garageColor){
alert("your car is " + garageColor);
} else {
car.color = "red";
}
答案 0 :(得分:1)
这是您问题的正确答案:
请参阅我的评论,以便更好地了解其工作原理。
if (favoriteColor) {
car.color = favoriteColor; // If you have a favorite color, choose the favorite color.
} else if (garageColor) {
car.color = garageColor; // If the garage color is known, choose the garage color.
} else {
car.color = 'red'; // Otherwise, choose the color 'red'.
}
alert('Your car is: ' + car.color);
<强> Try it Online! 强>
相关问题(进一步深入了解):
https://softwareengineering.stackexchange.com/q/289475
替代方法:
作为另一种可能性,您可以编写conditional (ternary) operation将所有逻辑压缩为单个语句。
alert('Your car is: ' + (car.color = favoriteColor ? favoriteColor : garageColor ? garageColor : 'red'));
答案 1 :(得分:0)
看起来你需要在if语句中使用double equals符号。检查相等性时使用==。试试这个:
car.color = favoriteColor || "red";
if (car.color == favoriteColor ){
alert("your car is " + favoriteColor);
} else if (car.color == garageColor){
alert("your car is " + garageColor);
} else {
car.color = "red";
}
答案 2 :(得分:0)
希望这段代码有用
function _showFavColor(getColor){
var favoriteColor = 'red';
var garageColor ="blue";
var carColor = getColor;
if (carColor == favoriteColor ){
alert("your car is " + favoriteColor);
} else if (carColor == garageColor){
alert("your car is " + garageColor);
} else {
carColor = "red";
}
}
_showFavColor('red');
_showFavColor('blue');
还要注意如何在js中完成等式检查。您可以关注此链接或谷歌 Which equals operator (== vs ===) should be used in JavaScript comparisons?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness
此外,如果您使用car.color,如果不创建汽车对象,则会抛出错误
'Uncaught SyntaxError: Unexpected token . '