【问题标题】:Boolean test as argument布尔测试作为参数
【发布时间】:2018-02-07 19:56:59
【问题描述】:

我想要这样的东西

let condition = function(name, cond) {
this.name = name;
this.func = (prop) => {
    if (cond) { 
        return true;
    }
    return false;
}

let snow = new condition("temperature", prop < 0);

我在一个单独的文件夹中有一个温度值和一个检查condition.func 是否返回真或假的函数。例如,如果温度低于 0 则不会下雪,这意味着我将调用 condition.func(temperature),这将执行代码 if (temperature &lt; 0){return true}
问题是当我定义雪时它会抛出未定义道具的错误...
我知道这是因为我希望覆盖一个甚至没有初始化的变量,但我不知道如何将布尔测试作为函数的参数来实现

【问题讨论】:

    标签: javascript function boolean conditional-statements


    【解决方案1】:

    您需要将带有输入参数的functionarrow-function 传递给您的condition,它将存储在cond 属性中。然后,当您调用 func 时,将参数传递到 func 并使用 cond 引用来调用您的 cond function,并使用给定的参数(如 cond(prop))。您还可以简化您的 func 函数并仅引用 cond

    let condition = function(name, cond) {
       this.name = name;
       this.func = cond;
    };
    
    let snow = new condition("temperature", prop => prop < 0);
    
    if(snow.func(-2)){
      console.log(`Snowing`);
    }

    【讨论】:

    • 我从来没有见过没有() => {}的箭头函数,你能解释一下prop => prop
    【解决方案2】:

    您可以只交出函数,而无需中间函数。对于条件,您需要一个函数,如p =&gt; p &lt; 0,而不仅仅是一个条件,如prop &lt; 0。这仅适用于硬编码或eval,作为字符串,而不是作为参数。

    function Condition (name, cond) {
        this.name = name
        this.func = cond
    }
    
    let snow = new Condition("temperature", p => p < 0);
    
    console.log(snow.func(5));
    console.log(snow.func(-5));

    【讨论】:

      【解决方案3】:

      您需要一种方法来检查该值是否符合您的条件。请参阅下文了解可能的解决方案。

      let condition = function(name, predicate) {
        this.name = name
        // func will take a single value, the temperate to check
        this.func = (prop) => {
            // Execute the predicate method with the provided value.
            return predicate(prop);
        }
      }
      
      /**
       * This method will check your condition, it takes a single value as a param
       */
      function snowPredicate(value) {
        // It can only snow when value is less than 0.
        return (value < 0);
      }
      
      // Set the condition for snow, pass the predicate method as the check.
      let snow = new condition("temperature", snowPredicate)
      
      // Check if it can snow when it is 10 degrees and -1 degrees.
      console.log(snow.func(10));
      console.log(snow.func(-1));

      【讨论】:

        猜你喜欢
        • 2023-02-14
        • 1970-01-01
        • 2014-07-02
        • 1970-01-01
        • 2013-08-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-16
        相关资源
        最近更新 更多