【问题标题】:Stuck. New to JS. Trying to figure this out since hours卡住。 JS新手。从几个小时开始就试图解决这个问题
【发布时间】:2019-03-26 11:58:10
【问题描述】:

我无法解决练习三和四。我会很高兴得到一些帮助。提前谢谢!

function exerciseThree(str){
  // In this exercise, you will be given a variable, it will be called: str
  // On the next line create a variable called 'length' and using the length property assign the new variable to the length of str


  // Please write your answer in the line above.
  return length; 
}

function exerciseFour(num1){
  // In this exercise, you will be given a variable, it will be called: num1
  // On the next line create a variable called 'rounded'. Call the Math global object's round method, passing it num1, and assign it to the rounded variable.
  var num1 = rounded;
  math.round (num1); 

  // Please write your answer in the line above.
  return rounded;
}

【问题讨论】:

  • 似乎已经有了很好的说明。你被困在哪里了?你试过什么?
  • 网上有很多javascript教程,如果这些练习太难,你应该通过它们来学习。

标签: javascript variable-assignment string-length global-object


【解决方案1】:

这些练习试图教你如何声明变量以及如何为变量赋值。

变量就像为您保存值的小容器。例如,我可以做一个小容器来保存你的名字。由于在 JavaScript 中声明变量的方法之一是使用 var 关键字,因此我可以编写如下内容:

var name = "Sevr";

我用var 关键字制作了一个容器,并将其命名为name。这个name 容器现在包含你的名字Sevr。您现在可以一遍又一遍地键入Name,而不是一遍又一遍地输入Sevr。但是,这并没有太大的区别。 Sevrname 都包含相同数量的字符。让您的变量包含您不想一遍又一遍地输入的信息会更有意义。

所以练习三希望你声明一个名为 length 的变量,并让它保存提供给它的任何字符串的长度。

function exerciseThree(str) {
        var length = str.length
        return length;
}

上面的这个函数接受一个字符串,你创建一个名为length的变量,其中包含该字符串的长度。

现在,如果我们将任何字符串传递给它,它会告诉我们它们的长度。如果我们将您的姓名 Sevrname 传递给它,我们将看到它们都返回 4:

exerciseThree("name") // 4
exerciseThree("Sevr") // 4

在第四个练习中,概念是相同的。练习想告诉你,你可以创建一个简单的变量名,它可以为你保留一些复杂的值。这一次它希望你声明一个名为 rounded 的变量,它保留一个数字的舍入值。

function exerciseFour(num1) {
    var rounded = Math.round(num1)
    return rounded;
}

而且,现在如果你向这个函数传递一个带小数的数字,它会为你四舍五入。

exerciseFour(4.5) // 5

【讨论】:

    【解决方案2】:

    这些练习的措辞非常混乱。你从哪里弄来的?

    不管怎样,这里有答案,希望对你有所帮助:

    function exerciseThree(str){
      // In this exercise, you will be given a variable, it will be called: str
      // On the next line create a variable called 'length' and using the length property assign the new variable to the length of str
      var length = str.length
      // Please write your answer in the line above.
      return length; 
    }
    
    function exerciseFour(num1){
      // In this exercise, you will be given a variable, it will be called: num1
      // On the next line create a variable called 'rounded'. Call the Math global object's round method, passing it num1, and assign it to the rounded variable.
      var rounded = Math.round(num1)
      // Please write your answer in the line above.
      return rounded;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-16
      • 1970-01-01
      • 2015-09-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多