![](/img/trans.png)
[英]How to assign a return value from a function directly to an object literal
[英]How to use return value from another JS function in object literal
我有一系列兩個方法,其中第二個方法必須使用第一個的返回值。 因此,在我的代碼中,如下所示, totalRoute
需要從totalInvoiced
返回的值(即value3
)來計算其值,然后將其顯示在我正在構建的寄存器中。 totalRoute
將等於totalInvoiced
減去的總和notCollected
, notCollectedLate
, expenditure1
和expenditure2
。
我的問題是,當我插入notCollected
, notCollectedLate
, expenditure1
和expenditure2
的值時, totalRoute
值為NaN
。 我想那是因為我沒有使用來自totalInvoiced
的返回值,或者該值未正確傳遞。 為什么我的函數沒有從totalInvoiced
獲取或使用值?
我的JS代碼在這里:
var A = {
today: document.getElementById("today"),
displayDate: function () {
var cD = new Date();
var day = cD.getDate();
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"];
var year = cD.getFullYear();
var today1 = A.today;
today1.innerHTML = (day + "/" + months[cD.getMonth()] + "/" + year);
},
invoiced: document.getElementById("invoiced"),
lastInvoiced: document.getElementById("lastinvoiced"),
totalInvoiced: function () {
var value1 = parseFloat(A.invoiced.value);
var value2 = parseFloat(A.lastInvoiced.value);
if (isNaN(value1))
value1 = 0;
if (isNaN(value2))
value2 = 0;
var totalInvoiced1 = value1 + value2;
var value3 = document.getElementById("daytotal").value = totalInvoiced1 + "€";
console.log(value3);
return value3;
},
notCollected: document.getElementById("notcollected"),
notCollectedLate: document.getElementById("notcollectedlate"),
expenditure1: document.getElementById("expenditure1"),
expenditure2: document.getElementById("expenditure2"),
totalRoute: function () {
var value4 = parseFloat(A.notCollected.value);
var value5 = parseFloat(A.notCollectedLate.value);
var value6 = parseFloat(A.expenditure1.value);
var value7 = parseFloat(A.expenditure2.value);
if (isNaN(value4))
value4 = 0;
if (isNaN(value5))
value5 = 0;
if (isNaN(value6))
value6 = 0;
if (isNaN(value7))
value7 = 0;
var totalExp = (value4 + value5 + value6 + value7);
var value3 = A.totalInvoiced();
var tRoute = value3 - totalExp;
var value8 = document.getElementById("total").value = tRoute + "€";
console.log(value8);
return value8;
}
};
window.onload = A.totalInvoiced();
window.onload = A.displayDate();
A.invoiced.addEventListener("change", A.totalInvoiced, false);
A.lastInvoiced.addEventListener("change", A.totalInvoiced, false);
A.notCollected.addEventListener("change", A.totalRoute, false);
A.notCollectedLate.addEventListener("change", A.totalRoute, false);
A.expenditure1.addEventListener("change", A.totalRoute, false);
A.expenditure2.addEventListener("change", A.totalRoute, false);
totalInvoiced中返回的value3
包含歐元字符。 只需將totalInvoiced的返回值更改為totalInvoiced1
而不是value3
,即可獲得我認為您正在尋找的功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.