gpt4 book ai didi

javascript - 如何使用内置局部变量参数编写函数?

转载 作者:行者123 更新时间:2023-11-29 23:21:07 25 4
gpt4 key购买 nike

我对 javascript 还是很陌生,所以如果这很烦人,我深表歉意。所以我有一个我不熟悉并试图解决的非常奇怪的问题。我要完成下面列出的功能“攀登”。我需要在函数 climb 中使用内置的局部变量参数。我不能改变函数来接收参数,这个练习的目的是在函数范围内使用局部参数变量。任何帮助是极大的赞赏!提前致谢。

这是函数必须做的:

If there is a string at arguments[0] but arguments[1] is falsy, return "On belay?". 

If there is a string at arguments[0], and true at arguments[1],
return "Climbing!"

Otherwise, return "Let's set up the belay rope before we climb."

它还必须通过所有这些测试:

should be a function that does not have built-in parameters
should return "Let's set up the belay rope before we climb." if called as climb()
should return "Climbing!" if called with climb("Benny", true)
should return "Climbing!" if called with climb("any string here", true)
should return "On belay?" if called with climb("Benny", false)
should return "On belay?" if called with climb("any string here")

这是我提供的功能的开始:

function climb(){

//CODE HERE - DO NOT TOUCH THE CODE ABOVE!

}

这是我正在尝试的:

function climb(){

//CODE HERE - DO NOT TOUCH THE CODE ABOVE!

if(arguments[0]){
if(arguments[1]==false){
return "On belay?";
} else {
return "Climbing!";
}
} else {
return "Let's set up the belay rope before we climb.";
}
}

这通过了除此之外的所有测试: 应该返回“On belay?”如果调用 climb("这里有任何字符串")

最佳答案

您可以向相关的 if 语句添加第二个条件,以使用 typeof 检查它是否具有 bool 值(真/假)。像这样的运算符:

function climb(){

//CODE HERE - DO NOT TOUCH THE CODE ABOVE!

if(arguments[0]){
if(arguments[1]==false || (typeof(arguments[1]) != typeof(true))){
return "On belay?";
} else {
return "Climbing!";
}
} else {
return "Let's set up the belay rope before we climb.";
}
}

在上面,typeof 检查 argument[1] 是否是 boolean 类型的值。


jsFiddle: https://jsfiddle.net/AndrewL64/k8ykedz3/


正如@KirkLarkin 所提到的,一种更短更简洁的方法是使用 ! 来检查它是否像这样:

function climb(){

//CODE HERE - DO NOT TOUCH THE CODE ABOVE!

if(arguments[0]){
if(!arguments[1]){
return "On belay?";
} else {
return "Climbing!";
}
} else {
return "Let's set up the belay rope before we climb.";
}
}

关于javascript - 如何使用内置局部变量参数编写函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50613034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com