如何从一个函数中获取一个数字并在另一个函数中使用它?



我正在为我的类编写一个提示计算器,我们需要创建3个函数。第二个函数需要使用我在第一个函数中得到的数字,第三个函数需要使用我在第二个函数中得到的数字。

What I tried:

// Grab the HTML Elements you want to work with
const billTotal = document.querySelector("#billTotal");
const tipPercent = document.querySelector("#tipPercent");
const noPeople = document.querySelector("#noPeople");
const calcTip = document.querySelector("#calcTip");
const resultsDiv = document.querySelector("#resultsDiv");

// Add event Listeners for your elements
calcTip.addEventListener("click", function() {
getTipAmount();
getBillTotal();
});
// Declare any functions you will need 
function getTipAmount() {
let total = Number(billTotal.value);
let tip = Number(tipPercent.value);
let output = total * (tip / 100);
let tipAmount = output.toFixed(2);
console.log(tipAmount);
}
function getBillTotal() {
let billAmount = Number(billTotal.value);
let billTotalur = tipAmount + billAmount;
let billTotalr = billTotalur.toFixed(2);
console.log(billTotalr)
}
function amountPerPerson() {
}

我期望tipAmount被添加到billAmount,但是我收到tipAmount没有定义。

您需要添加一个返回语句来将其存储在更高作用域的变量中,然后将其传递给下一个函数:

// Grab the HTML Elements you want to work with
const billTotal = document.querySelector("#billTotal");
const tipPercent = document.querySelector("#tipPercent");
const noPeople = document.querySelector("#noPeople");
const calcTip = document.querySelector("#calcTip");
const resultsDiv = document.querySelector("#resultsDiv");

// Add event Listeners for your elements
calcTip.addEventListener("click", function() {
const tipAmount = getTipAmount();
const billTotalr = getBillTotal(tipAmount);
console.log(tipAmount);
console.log(billTotalr)
});
// Declare any functions you will need 
function getTipAmount () {
const total = Number(billTotal.value);
const tip = Number(tipPercent.value);
const output = total * (tip / 100);
const tipAmount = output.toFixed(2);
return tipAmount  
}
function getBillTotal (tipAmount) {
const billAmount = Number(billTotal.value);
const billTotalur = tipAmount + billAmount;
const billTotalr = billTotalur.toFixed(2);

return billTotalr
}
function amountPerPerson() {
}

这是将结果从一个函数提供给另一个函数的一种方法。在JavaScript中有很多种编写函数的方法,但这是最基本的方法之一。

function func1() {
return 'Hello';
}
function func2(string) {
return string + ' world';
}
const result1 = func1();
const result2 = func2(result1);
console.log(result2);

最新更新