提问人:Maz 提问时间:1/7/2022 最后编辑:user3840170Maz 更新时间:1/7/2022 访问量:481
当我有一个条件“if (bool = true)”时,else 分支永远不会被命中。为什么?
When I have a condition `if (bool = true)`, the else branch is never hit. Why?
问:
挑战如下:
创建一个接受字符串的函数 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."
答:
2赞
neku894
1/7/2022
#1
除了每个人都已经指出的部分(您可以使用此部分)之外,您忘记添加语句了。它应该是:if (bool = true)
if (bool)
return
else
} 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 ?
评论
if (bool = true)
这将分配给布尔。你需要用它来做一个比较,或者只是true
if (bool === true)
if (bool)
if (bool = true)
完全没用。这是一个任务,而不是比较,所以结果总是正确的。true
false
if (bool)
if (!bool)