【问题标题】:How to write a function using the built-in local variable arguments?如何使用内置的局部变量参数编写函数?
【发布时间】:2018-05-30 20:40:24
【问题描述】:

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

这是函数必须做的:

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.";
  }
}

这通过了除此之外的所有测试: should return "On belay?" if called with climb("any string here")

【问题讨论】:

  • 关键是你如何检查“假”值。

标签: javascript arguments


【解决方案1】:

您可以使用typeof 运算符向相关的 if 语句添加第二个条件,以检查它是否具有布尔值(真/假),如下所示:

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.";
  }
}

【讨论】:

  • 非常感谢!我知道我需要调整的是 if 语句。我只是不确定我需要做什么。在询问之前,我曾尝试过与此非常相似的事情。
  • @stoney_24 很高兴我能帮上忙! typeof 也无数次帮助我解决类似的问题。非常漂亮的运算符。
  • 这有点不必要 - 您需要做的就是if(!arguments[1]),它会简单地检查arguments[1] 是否按照要求中的描述为假。
  • @KirkLarkin 同意。此外,您不需要两个条件。请将其添加为答案,我会投票赞成的人。干杯。
  • 没问题。随意将其添加到您自己的答案中作为改进或替代。
猜你喜欢
  • 2017-03-11
  • 2011-02-14
  • 2015-06-25
  • 2012-12-12
  • 2021-04-08
  • 1970-01-01
  • 2022-08-02
  • 1970-01-01
相关资源
最近更新 更多