有没有替代使用IF/ELSE语句的方法?(涉及IT技术)

3

问题

更多的是出于好奇,但我想知道如何重构一个 if 语句以使其更加简洁 / 不易出错。从我所了解的来看,多态性可能会有用?

在这个例子中,如果 color:'red' 为真,我只想返回第一辆车。

Coffeescript

example: () ->
    cars = [{color:'red', reg:'111'},{color:'blue', reg:'666'}]
    if cars[0].color is 'red' 
    then cars[0]
    else cars[1]

Javascript

  example: function() {
    var cars = [{color:'red',reg:'111'},{color:'blue',reg:'666'}];
    if (cars[0].color === 'red') {
      return cars[0];
    } else {
      return cars[1];
    }
  }

我理解这个问题可能因为模糊不清的性质而被关闭或移动


我不确定多态在这里是否有用,但似乎汽车可以拥有自己的构造函数,并在其原型上具有getColor方法。 - Willem D'Haeseleer
它被称为“速记”,你可以在这里阅读一些JavaScript速记技巧http://www.jquery4u.com/javascript/shorthand-javascript-techniques/ :) - thinklinux
在Python中,三元语句的写法是:1<10 and 5 or 6,它会返回 5 - Pe Dro
6个回答

6
您可以使用三元运算符,其语法为condition ? result1 : result2;。它是一种简洁的条件语句,可用于在不使用if语句的情况下根据条件返回不同的结果。
return cars[0].color === 'red' ? colors[0] : colors[1]

6

? : 运算符就是一个“更简洁”的if-else语句。

http://msdn.microsoft.com/zh-cn/library/ty67wk28.aspx

classify = (input < 0) ? "negative" : "positive";

还有适用于更大组合的switch语句:

http://www.w3schools.com/js/js_switch.asp

switch(n)
{
case 1:
  execute code block 1
  break;
case 2:
  execute code block 2
  break;
default:
  code to be executed if n is different from case 1 and 2
}

多态是一个抽象的概念,而不是一种编写语句的方式。它是创建方法/函数/类等的实践,其中类型至少有些模糊。因此,如果将整数作为参数1提供给同一方法,与将数组提供到相同参数时将返回相同的结果。


2

仅供娱乐:

// red     -> +false -> 0
// not red -> +true  -> 1
return cars[+(cars[0].color !== 'red')];

如果我只考虑娱乐性和好玩程度,那么这就是答案。 :D - mikedidthis

1

当你不想使用 if-else 语句时,通常会使用三元运算符 ?

example: function() {
    var cars = [{color:'red',reg:'111'},{color:'blue',reg:'666'}];

    return cars[0].color === 'red' ? cars[0] : cars[1];
  }

1
将汽车转化为一个对象:
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());

例子:http://jsfiddle.net/YthH8/

请记住,JavaScript 中有许多使用对象/继承的方式。
CoffeeScript 有自己的语法糖用于使用类 => http://coffeescript.org/#classes


谢谢答复。我相信我的问题仍然存在,因为我必须正确地查看颜色“红色”的测试? - mikedidthis

0

const example = () => {
    var cars = [{color:'red',reg:'111'},{color:'blue',reg:'666'}];
    return (cars[0].color === 'red' && cars[0]) ||
        cars[1];
}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接