【问题标题】:When I have a condition `if (bool = true)`, the else branch is never hit. Why?当我有条件 `if (bool = true)` 时,永远不会命中 else 分支。为什么?
【发布时间】:2022-01-06 18:35:49
【问题描述】:

挑战如下:

创建一个接受字符串的函数 makePlans。这个字符串应该是一个名字。函数 makePlans 应该调用函数 callFriend 并返回结果。 callFriend 接受一个布尔值和一个字符串。将friendsAvailable变量和名称传递给callFriend。

创建一个接受布尔值和字符串的函数 callFriend。如果布尔值为真,则 callFriend 应返回字符串“本周末使用 NAME 制定的计划”。否则它应该返回“这个周末每个人都很忙”。>

这是我写的:

let friendsAvailable = true;

function makePlans(name) {
  return callFriend(friendsAvailable, name);
}

function callFriend(bool, name) {
  if (bool = true) {
    return 'Plans made with ' + (name) + ' this weekend'
  } else {
    'Everyone is busy this weekend'
  }

}

console.log(makePlans("Mary")) // should return: "Plans made with Mary this weekend'
friendsAvailable = false;
console.log(makePlans("James")) //should return: "Everyone is busy this weekend."

【问题讨论】:

  • if (bool = true)分配 true 到布尔值。您需要使用if (bool === true) 进行比较,或者只使用if (bool)
  • if (bool = true)完全没用。这是一个赋值,而不是比较,所以结果总是正确的。
  • 一般来说,避免与truefalse比较。只需写if (bool)if (!bool)
  • 谢谢 :) 很有帮助

标签: javascript assignment-operator equality-operator


【解决方案1】:

除了大家已经指出的if (bool = true)部分(你可以使用if (bool)),你忘了在else声明中添加return。应该是:

} else {
    return 'Everyone is busy this weekend'
}

【讨论】:

    【解决方案2】:

    完整代码:

    let friendsAvailable = true;
    
    function makePlans(name)
      {
      return callFriend(friendsAvailable, name);
      }
    
    function callFriend(bool, name)
      {
      if (bool)  // or  if (bool===true), but testing if true is true is a little bit redundant
        {
        return 'Plans made with ' + (name) + ' this weekend'
        } 
      else 
        {
        return 'Everyone is busy this weekend'
        }
      }
    
    console.log(makePlans("Mary")) // should return: "Plans made with Mary this weekend'
    friendsAvailable = false;
    console.log(makePlans("James")) //should return: "Everyone is busy this weekend."

    但是,如果您想给老师留下深刻印象,请这样做:

    const
      callFriend = 
        (bool, name) =>
          bool 
           ? `Plans made with ${name} this weekend` 
           : 'Everyone is busy this weekend' 
    
    const makePlans = name => callFriend(friendsAvailable, name);
    
    
    let friendsAvailable = true
    
    console.log(makePlans('Mary')) 
    
    friendsAvailable = false
    
    console.log(makePlans('James')) 

    一些帮手:
    Arrow function expressions
    Conditional (ternary) operator

    【讨论】:

    • 在 15krep 之前,我希望您知道:既不能解释发生了什么变化,也不能解释解决问题的原因的代码转储不是很有用。
    • @jonrsharpe 我相信以身作则的美德,不是吗?
    • 如果这是您的定义所要求的,显然不是。
    • @jonrsharpe j'ai pas compris, de quelle définition parlez vous ?
    猜你喜欢
    • 2020-07-05
    • 1970-01-01
    • 1970-01-01
    • 2016-02-08
    • 2021-08-01
    • 2019-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多