为学校和阵列工作项目正在给我带来严重的问题。他们正在返回错误:
Uncaught ReferenceError: oddNumbers is not defined.
我完全按照本网站上的其他问题提出要求,但无济于事。你可以在ScriptManager中看到“类”(因为我习惯于Java和C#),oddNumbers和evenNumbers不能被推入。请告诉我什么是错的。
var manager = new ScriptManager();
function enterNumber() {
var number = prompt("Enter a number");
if (manager.addNumber(number)) {
document.getElementById("even").innerHTML = manager.getEvenNumbers();
document.getElementById("odd").innerHTML = manager.getOddNumbers();
document.getElementById("sum").innerHTML = manager.sum;
document.getElementById("average").innerHTML = manager.average;
}
}
function ScriptManager() {
this.count = 0;
this.oddCount = 0;
this.evenCount = 0;
this.sum = 0;
this.average = 0;
this.oddNumbers = [];
this.evenNumbers = [];
this.addNumber = function(number) {
if (!isNaN(parseInt(number))) {
number = parseInt(number);
if (number % 2 == 0) {
evenNumbers.push(number);
evenCount++;
count++;
} else {
oddNumbers.push(number);
oddCount++;
count++;
}
} else {
alert(number + " is not a valid number.");
return false;
}
for (var x = 0; x < oddCount; x++) {
sum += oddNumbers[x];
}
for (var x = 0; x < evenCount; x++) {
sum += evenNumbers[x];
}
average = sum / count;
return true;
};
this.getEvenNumbers = function() {
var stream = "";
var first = true;
for (var x = 0; x < evenCount; x++) {
if (!first) {
stream + ", ";
}
stream += String.valueOf(evenNumbers[x]);
if (first) {
first = false;
}
}
return stream;
}
this.getOddNumbers = function() {
return "bleh";
}
}
答案 0 :(得分:1)
您需要在所有对象属性之前使用this.
前缀。
this.addNumber = function(number) {
if (!isNaN(parseInt(number))) {
number = parseInt(number);
if (number % 2 == 0) {
this.evenNumbers.push(number);
this.evenCount++;
this.count++;
} else {
this.oddNumbers.push(number);
this.oddCount++;
this.count++;
}
} else {
alert(number + " is not a valid number.");
return false;
}
for (var x = 0; x < oddCount; x++) {
this.sum += this.oddNumbers[x];
}
for (var x = 0; x < evenCount; x++) {
this.sum += this.evenNumbers[x];
}
this.average = this.sum / this.count;
return true;
};
答案 1 :(得分:0)
在javascript中,您必须在成员变量前使用this
来访问它们。所以:
oddNumbers.push(number);
需要:
this.oddNumbers.push(number);
并且,类似于所有其他成员变量。