当我有一个条件“if (bool = true)”时,else 分支永远不会被命中。为什么?

When I have a condition `if (bool = true)`, the else branch is never hit. Why?

提问人:Maz 提问时间:1/7/2022 最后编辑:user3840170Maz 更新时间:1/7/2022 访问量:481

问:

挑战如下:

创建一个接受字符串的函数 makePlans。此字符串应为名称。函数 makePlans 应调用函数 callFriend 并返回结果。callFriend 接受布尔值和字符串。将 friendsAvailable 变量和 name 传入 callFriend。

创建一个接受布尔值和字符串的函数 callFriend。如果布尔值为 true,则 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."

JavaScript 赋值运算符 equality-operator

评论

1赞 Nicholas Tower 1/7/2022
if (bool = true)这将分配给布尔。你需要用它来做一个比较,或者只是trueif (bool === true)if (bool)
0赞 jonrsharpe 1/7/2022
if (bool = true)完全没用。这是一个任务,而不是比较,所以结果总是正确的。
1赞 Barmar 1/7/2022
通常,请避免将 和 进行比较。只需写或truefalseif (bool)if (!bool)
0赞 Maz 1/7/2022
谢谢:)很有帮助

答:

2赞 neku894 1/7/2022 #1

除了每个人都已经指出的部分(您可以使用此部分)之外,您忘记添加语句了。它应该是:if (bool = true)if (bool)returnelse

} else {
    return 'Everyone is busy this weekend'
}
-3赞 Mister Jojo 1/7/2022 #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')) 

一些帮助程序:
箭头函数表达式
条件(三元)运算符

评论

3赞 jonrsharpe 1/7/2022
到 15krep 时,我希望您知道:既不解释更改的内容也不解释为什么解决问题的代码转储不是很有用。
0赞 Mister Jojo 1/7/2022
@jonrsharpe我相信以身作则的美德,不是吗?
1赞 jonrsharpe 1/7/2022
如果这是你的定义所要求的,显然不是。
0赞 Mister Jojo 1/7/2022
@jonrsharpe j'ai pas compris, de quelle définition parlez vous ?