首页 > 解决方案 > 当我认为它已定义时,在我的 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"

标签: javascriptundefinedjavascript-objects

解决方案


将您的 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;

};

推荐阅读