[英]How do i convert “[object Object]” to a number
I have been set a task, using an external IFFE file, to create an app that works out the cost of fuel for a fleet of cars using the functions inside the IFFE. 我已经设置了一个任务,使用外部IFFE文件,创建一个应用程序,计算使用IFFE内部功能的车队的燃料成本。 Then display it in a box. 然后将其显示在一个框中。
The IFFE can be see Here , i have been told by the people that set me the task that the following code should work to call the correct function IFFE可以看到这里 ,人们告诉我,下面的代码应该用来调用正确的函数的任务
var fuel = new fuelCalc();
// On the button press
miles = 10000;
var cost = fuel.cost(miles);
Then doing the following should put it into the text box, 然后执行以下操作应将其放入文本框中,
document.getElementById("TotalCost").value = cost;
However, all it does is put the following in the text box 但是,它所做的就是在文本框中添加以下内容
[object Object] [对象]
What do i need to add to make it show the calculated amount? 我需要添加什么才能显示计算出的金额?
您需要指定一年,例如document.getElementById("TotalCost").value = cost[2013];
Based on your code, it looks like your function fuelCalc.cost is actually returning an object though. 根据您的代码,看起来您的函数fuelCalc.cost实际上是返回一个对象。
Do you need to do further calculations within the function, maybe: 您是否需要在函数内进行进一步的计算,可能:
fuelCalc.prototype.cost = function ( annualMileage, start, end ) {
var costPerLitre = this.costPerLitre;
var averageMPG = this.averageMPG;
var startYear = start || 1989;
var endYear = end || 2020;
var totalYears = endYear - startYear;
var data = {};
var totalCost = 0;
for (var year = startYear, t = endYear; year <= t; year += 1) {
data[year] = this.costIn( year, annualMileage );
totalCost += data[year]
}
return totalCost;
}
The reason you are seeing [object Object]
is because fuel.cost(miles)
does not return the cost value but a hash
or instance of cost
class maybe. 您看到[object Object]
的原因是因为fuel.cost(miles)
不返回成本值,但可能是cost
类的hash
或实例。
Try debugging this javascript on browser's javascript console, by setting a breakpoint at the line: 尝试在浏览器的javascript控制台上调试此javascript,方法是在该行设置断点:
document.getElementById("TotalCost").value = cost;
At this moment in Console, just print the cost
variable. 此时在Console中,只需打印cost
变量即可。 It will list the object structure and you can extract relevant data from that. 它将列出对象结构,您可以从中提取相关数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.