JavaScript:使用变量的计算器

时间:2014-09-06 11:25:45

标签: javascript jquery

我有一个问题,我无法让我的JavaScript计算器工作。在浏览器中显示时,该部分显示实际的代码行而不是返回的答案。这就是我到目前为止所拥有的。计算在函数b()中,并打印在底部的document.write()


JavaScript的:

//*Note that this is an external JavaScript file*
function a(a1,a2,a3) {
    this.a1 = a1;
    this.a2 = a2;
    this.a3 = a3;
    this.a4 = b;
}

var abc = new a("2", "80", "1000");
var def = new a("1.5", "40", "512");
var ghi = new a("1", "20", "256");

//Below is the calulation function I'm having problems with
function b() {
    var calculation;
    calculation = 500;
    calculation+=(this.a1 = 2) ? 200 : 100;
    calculation+=(this.a2 = 80) ? 50 : 25;
    calculation+=(this.a3 = 1000) ? 150 : 75;
    return calculation;
}

var returned_value_abc = abc.a4();
var returned_value_def = def.a4();
var returned_value_ghi = ghi.a4();

document.write("Abc object: ");
document.write("<br/>");
//Below is code to print out returned calculation value
document.write("Value: "+abc.a4);
document.write("<br/>");
document.write("<br/>");
document.write("Def object: ");
document.write("<br/>");
//Below is code to print out returned calculation value
document.write("Value: "+def.a4);
document.write("<br/>");
document.write("<br/>");
document.write("Ghi object: ");
document.write("<br/>");
//Below is code to print out returned calculation value
document.write("Value: "+ghi.a4);

1 个答案:

答案 0 :(得分:5)

你的问题很可能就是这些问题:

calculation+=(this.a1 = 2) ? 200 : 100;
calculation+=(this.a2 = 80) ? 50 : 25;
calculation+=(this.a3 = 1000) ? 150 : 75;

括号中的=assignment,而不是equality comparison。使用

calculation += (this.a1 == 2) ? 200 : 100;
calculation += (this.a2 == 80) ? 50 : 25;
calculation += (this.a3 == 1000) ? 150 : 75;