【问题标题】:Convert a string representation of a comparison operator to an actual comparison operator将比较运算符的字符串表示形式转换为实际的比较运算符
【发布时间】:2016-05-24 13:55:01
【问题描述】:

我正在尝试在 JavaScript 中创建一个动态函数,我可以在其中将一个对象与另一个对象进行比较,将比较运算符作为字符串值传递给函数。

例如两个这样的对象:

{value: 1, name: "banana"}
{value: 2, name: "apples"}

我想比较香蕉和苹果,有没有一种方法可以传递比较运算符的字符串表示形式,然后将其用作函数中的实际比较运算符?

function compare (first, second, comparator) {

    return first.id (comparator) second.id;

}

e.g compare(apple,banana,"<=");
//return true

compare(apple,banana,"===");
//return false

当然,我可以在比较器字符串上使用 switch 或 if 语句来实现,即

 if (comparator === "<=")
    return first.id <= second.id
    if (comparator === "===")
    return first.id === second.id

但我想知道是否有更好更有效的方法来避免这种 switch/if 语句的需要。

【问题讨论】:

  • return eval("first.id "+comparator+" second.id");
  • 通常会将比较行为表示为一个函数,然后将其传入。您可以预定义它们,以便将它们称为 LESSTHAN 等。然后在您的 compare 函数中您需要做的所有事情是调用函数。

标签: javascript comparison-operators


【解决方案1】:

虽然这在某些语言中可能是可能的,但 JavaScript 不是其中之一。

我个人认为这是一个坏主意,因为它危险地接近eval 领土。我认为您应该将运营商列入白名单并定义他们的行为:

switch(comparator) {
    case "<=": return first.id <= second.id;
    case "===": return first.id === second.id;
    // ...
    // you can have synonyms:
    case ">=":
    case "gte": return first.id >= second.id;
    // or even nonexistant operators
    case "<=>": // spaceship!
        if( first.id === second.id) return 0;
        if( first.id < second.id) return -1;
        return 1;
    // and a catch-all:
    default:
        throw new Error("Invalid operator.");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-28
    • 2012-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-16
    • 2019-07-25
    • 1970-01-01
    相关资源
    最近更新 更多