2014-09-06 2 views
-1

У меня проблема, когда я не могу заставить свой калькулятор JavaScript работать. При отображении в браузере эта часть отображает фактические строки кода вместо возвращаемого ответа. Это то, что у меня есть до сих пор. Расчет производится в функции b() и напечатан в нижней части окна document.write().JavaScript: Калькулятор с использованием переменных


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

Не используйте document.write: http://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice –

ответ

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; 
Смежные вопросы