[英]Pass values from an array within a function as params in another function JavaScript
I want to use the values in the array userInfo as parameters in the getBMR function. 我想将数组userInfo中的值用作getBMR函数中的参数。 How do I do that?
我怎么做?
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) { // ... }
Been googling like crazy but I can't seem to find the solution. 像疯了一样谷歌搜索,但我似乎找不到解决方法。 Using the console.log after the array declaration I can clearly see that the array stores the data.
在数组声明之后使用console.log ,我可以清楚地看到数组存储了数据。 My problem is getting this data outside the function.
我的问题是在函数之外获取此数据。
Here's my HTML: 这是我的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>
Really appreciating all the help that I can get! 非常感谢我能获得的所有帮助!
Thanks! 谢谢!
If your parameters are consistent and the list doesn't need to be dynamic you should be able to do: 如果您的参数是一致的,并且列表不需要是动态的,则应该可以:
function getBMR(userInput()[0], userInput()[1], userInput()[2], userInput()[3]) {
// ...
}
The problem is that when you have a var declared, its scope is only until the function finishes execution. 问题在于,当您声明var时,其作用域仅在函数完成执行之前。 So, i think a better way of doing this is to have separate functions for the parameters you need.
因此,我认为更好的方法是为所需的参数提供单独的功能。 Something like:
就像是:
function getLenght() {
return document.getElementById('length').value;
}
So whenever you call getBMR you would first declare and assign the other variables like so: 因此,每当调用getBMR时,您都将首先声明并分配其他变量,如下所示:
var length = getLength() ;
getBMR(length,...) ;
And also, an even better way would be to use jQuery where you can do: 而且,更好的方法是使用jQuery:
$. ("#length").val();
And this will return the value of the input. 这将返回输入的值。
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.