javascript - 当我认为它已定义时,在我的 JavaScript 代码中出现“未定义”错误
问题描述
我正在为 SkillCrush 开发一个项目并且收到“未定义”错误,当我觉得好像我已经在代码顶部定义了变量时。我 100% 知道我做错了什么,但不确定是什么。有什么建议么?
var createPolitician = function (name)
{
var politician = {}; //is this not defined here?
politician.name = name;
politician.electionResults = null;
politician.totalVotes = 0;
return politician;
};
var oscar = createPolitician("Oscar Jiminez");
var luke = createPolitician("Luke Spencer");
oscar.electionResults = [5, 1, 7, 2, 33, 6, 4, 2, 1, 14, 8, 3, 1, 11, 11, 0, 5, 3, 3, 3, 7, 4, 8, 9, 3, 7, 2, 2, 4, 2, 8, 3, 15, 15, 2, 12, 0, 4, 13, 1, 3, 2, 8, 21, 3, 2, 11, 1, 3, 7, 2];
luke.electionResults = [4, 2, 4, 4, 22, 3, 3, 1, 2, 15, 8, 1, 3, 9, 0, 6, 1, 5, 5, 1, 3, 7, 8, 1, 3, 3, 1, 3, 2, 2, 6, 2, 14, 0, 1, 6, 7, 3, 7, 3, 6, 1, 3, 17, 3, 1, 2, 11, 2, 3, 1];
oscar.electionResults[9] = 1;
luke.electionResults[9] = 28;
oscar.electionResults[4] = 17;
luke.electionResults[4] = 38;
oscar.electionResults[43] = 11;
luke.electionResults[43] = 27;
console.log(oscar.electionResults);
console.log(luke.electionResults);
politician.countTotalVotes = function()
{
this.totalVotes = 0;
for (var i = 0; i < this.electionResults.length; i++);
{
this.totalVotes = this.totalVotes + this.electionResults[i];
}
}
oscar.countTotalVotes();
luke.countTotalVotes();
console.log(oscar.totalVotes);
console.log(luke.totalVotes);
错误:
"error"
"ReferenceError: politician is not defined
at reloyur.js:32:1"
解决方案
将您的 countTotalVotes 函数移动到您的 create 函数中:
var createPolitician = function (name)
{
var politician = {};
politician.name = name;
// set to an empty array so this is defined
politician.electionResults = [];
politician.totalVotes = 0;
// here politician exists, add a function to the object that you can call later
politician.countTotalVotes = function()
{
this.totalVotes = 0;
for (var i = 0; i < this.electionResults.length; i++)
{
this.totalVotes = this.totalVotes + this.electionResults[i];
}
}
return politician;
};
推荐阅读
- ruby-on-rails - Rails admin级联下拉菜单如何?
- html - Whatsapp 点击聊天“无法打开链接”错误 Chrome Android/iPhone
- django - django 图像无法从默认值更新
- flutter - 在 Flutter 中将数据异步加载到 ChangeNotifier 模型中
- javascript - 在 Chart.js 中使用和读取来自 Knockout.js 的变量
- xml - DataTrigger 中的多个绑定
- html - 外部 div 背景可见 arround 内部 div 在 Chrome
- vb.net - LINQ to Entities 中的自定义函数?如何编写可接受的代码?
- postgresql - 全文搜索缺失词
- mysql - 进行 SQL 查询以给出这样的特定结果