首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在我认为已定义的JavaScript代码中得到一个“未定义”错误

在我认为已定义的JavaScript代码中得到一个“未定义”错误
EN

Stack Overflow用户
提问于 2018-07-17 23:53:41
回答 6查看 181关注 0票数 0

我正在为SkillCrush的一个项目工作,当我感觉好像在代码的顶部定义了变量时,我得到了一个“未定义”的错误。我100%知道我做错了什么,但不确定是什么。有什么建议吗?

代码语言:javascript
运行
复制
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);

错误:

代码语言:javascript
运行
复制
"error"
    "ReferenceError: politician is not defined
    at reloyur.js:32:1"
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51385683

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档