簡體   English   中英

從函數內的數組傳遞值作為另一個函數JavaScript中的參數

[英]Pass values from an array within a function as params in another function JavaScript

我想將數組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> 

非常感謝我能獲得的所有幫助!

謝謝!

如果您的參數是一致的,並且列表不需要是動態的,則應該可以:

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

問題在於,當您聲明var時,其作用域僅在函數完成執行之前。 因此,我認為更好的方法是為所需的參數提供單獨的功能。 就像是:

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

因此,每當調用getBMR時,您都將首先聲明並分配其他變量,如下所示:

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

而且,更好的方法是使用jQuery:

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

這將返回輸入的值。

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM