【问题标题】:Pass values from an array within a function as params in another function JavaScript将函数内数组中的值作为另一个函数 JavaScript 中的参数传递
【发布时间】:2017-03-06 20:27:43
【问题描述】:

我想将数组 userInfo 中的值用作 getBMR 函数中的参数。我该怎么做?

function userInput() {
  var gender = document.querySelector('input[name="gender"]:checked').value;
  var length = document.getElementById('length').value;
  var weight = document.getElementById('weight').value;
  var age = document.getElementById('age').value;
  
  if (length || weight || age === (strValue)) {
    length = parseInt(length);
    weight = parseInt(weight);
    age = parseInt(age);
    var userInfo = [gender, length, weight, age];
    return userInfo;
  }
}

function getBMR(gender, length, weight, age) {
// ...
}

一直在疯狂搜索,但我似乎找不到解决方案。在数组声明之后使用 console.log 我可以清楚地看到数组存储了数据。我的问题是在函数之外获取这些数据。

这是我的 HTML:

<html>

<head>
</head>

<body>

  <form action="">
    <input type="radio" name="gender" id="gender" value="male" checked="checked">Man<br>
    <input type="radio" name="gender" id="gender" value="female">Kvinna<br>

    <label>Längd</label>
    <input type="number" id="length"></input>

    <label>Vikt</label>
    <input type="number" id="weight"></input>

    <label>Ålder</label>
    <input type="number" id="age"></input>

    <button onclick="userInput()">Hämta BMR</button>
  </form>
  <p id="dittBMR"></p>
</body>

</html>

非常感谢我能得到的所有帮助!

谢谢!

【问题讨论】:

标签: javascript arrays function


【解决方案1】:

如果您的参数是一致的并且列表不需要是动态的,您应该可以这样做:

function getBMR(userInput()[0], userInput()[1], userInput()[2], userInput()[3]) {
// ...
}

【讨论】:

    【解决方案2】:

    问题是当你声明了一个 var 时,它的作用域只有在函数完成执行之前。所以,我认为这样做的更好方法是为您需要的参数设置单独的函数。比如:

    function getLenght() {
         return document.getElementById('length').value;
    } 
    

    因此,每当您调用 getBMR 时,您首先要声明并分配其他变量,如下所示:

    var length = getLength() ;
    getBMR(length,...) ;
    

    另外,一个更好的方法是在你可以做的地方使用 jQuery:

    $. ("#length").val();
    

    这将返回输入的值。

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2013-11-06
      • 2015-05-29
      • 1970-01-01
      • 2022-11-12
      • 2017-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-04
      相关资源
      最近更新 更多