Javascript 是否有替代使用IF/ELSE语句的方法
问题 更多是出于好奇,但我想知道如何将if语句重构为更干净/更不脆弱的语句。从我所读到的,多态性有什么用处 在这个例子中,我只想在Javascript 是否有替代使用IF/ELSE语句的方法,javascript,coffeescript,Javascript,Coffeescript,问题 更多是出于好奇,但我想知道如何将if语句重构为更干净/更不脆弱的语句。从我所读到的,多态性有什么用处 在这个例子中,我只想在color:'red'为真时返回第一辆车 咖啡脚本 example: () -> cars = [{color:'red', reg:'111'},{color:'blue', reg:'666'}] if cars[0].color is 'red' then cars[0] else cars[1] example:
color:'red'
为真时返回第一辆车
咖啡脚本
example: () ->
cars = [{color:'red', reg:'111'},{color:'blue', reg:'666'}]
if cars[0].color is 'red'
then cars[0]
else cars[1]
example: function() {
var cars = [{color:'red',reg:'111'},{color:'blue',reg:'666'}];
if (cars[0].color === 'red') {
return cars[0];
} else {
return cars[1];
}
}
Javascript
example: () ->
cars = [{color:'red', reg:'111'},{color:'blue', reg:'666'}]
if cars[0].color is 'red'
then cars[0]
else cars[1]
example: function() {
var cars = [{color:'red',reg:'111'},{color:'blue',reg:'666'}];
if (cars[0].color === 'red') {
return cars[0];
} else {
return cars[1];
}
}
我理解这个问题可能因为模糊性而关闭或移动你可以使用三元运算符,它的语法是
条件?结果1:结果2代码>
return cars[0].color === 'red' ? colors[0] : colors[1]
?:接线员就是那个,一个“清洁工”
多态性是一个抽象概念,不是一种编写语句的方式。这是一种创建方法/函数/类等的实践,其中类型至少有点模棱两可。因此,如果为参数1输入一个整数,同样的方法可以返回一个结果,就像将数组输入到同一个参数中一样。有一个ternar运算符?
主要用于不想使用if else
语句时:
example: function() {
var cars = [{color:'red',reg:'111'},{color:'blue',reg:'666'}];
return cars[0].color === 'red' ? cars[0] : cars[1];
}
只是为了好玩:
// red -> +false -> 0
// not red -> +true -> 1
return cars[+(cars[0].color !== 'red')];
将汽车变成物体:
function Car(options) {
this.options = {};
// Some default options for your object
$.extend(this.options, {
color: "green",
buildYear: 1990,
tires: 4,
brand: "merceded"
}, options);
}
// A method registered on the prototype
Car.prototype.getColor = function () {
return this.options.color;
};
var myToyota = new Car({
brand: "toyota"
});
console.log("My Toyota is: "+ myToyota.getColor());
例如:
请记住,在JavaScript中有许多方法可以使用对象/继承。
Coffee脚本在使用类=>
const示例=()=>{
var cars=[{color:'red',reg:'111'},{color:'blue',reg:'666'}];
返回(汽车[0]。颜色=='red'&&cars[0])||
汽车[1];
}
我不知道多态性在这里是否有用,但它看起来确实可以通过原型上的getColor方法获得自己的构造函数。它叫“速记”,你可以在这里阅读一些javascript速记:)谢谢你的回答。我相信我的问题仍然存在,因为我必须查看颜色红色的测试是否正确?如果我接受了笑声/乐趣因素,这将是答案:D