Javascript对象中的属性范围

时间:2022-08-30 10:10:03

I am receiving this error in my console. Error is happening within my for loop Not sure why but when I console.log(manchesterUnited.[0].salary); I get not errors. I am new to JS so it could be something minor. Uncaught TypeError: Cannot read property 'salary' of undefined.

我在控制台中收到此错误。错误发生在我的for循环中不确定为什么但是当我在console.log(manchesterUnited。[0] .salary);我没有错误。我是JS的新手,所以它可能是次要的。未捕获的TypeError:无法读取undefined的属性'salary'。

var footballer = function(name, position, age, salary, number) {
  this.name = name;
  this.position = position;
  this.age = age;
  this.salary = salary;
  this.number = number;
}

var manchesterUnited = [];
manchesterUnited[0] = new footballer("Zlatan", "striker", 37, 20, 9);
manchesterUnited[1] = new footballer("Rooney", "forward", 33, 15, 10);

var totalSalary = 0;

for(var i = 0; i <= manchesterUnited.length; i++){
    totalSalary = manchesterUnited[i].salary + totalSalary;
}

console.log(totalSalary);

Thank you.

2 个解决方案

#1


2  

In the for loop, you have:

在for循环中,您有:

i <= manchesterUnited.length

It should just be:

它应该只是:

i < manchesterUnited.length

#2


0  

You need to change this

你需要改变它

     for(var i = 0; i <= manchesterUnited.length; i++){
           totalSalary = manchesterUnited[i].salary + totalSalary;
     }

To this

      for(var i = 0; i < manchesterUnited.length; i++){
            totalSalary = manchesterUnited[i].salary + totalSalary;
      }`

The reason being that the <= operator causes you to pass beyond the length of your array by 1.

原因是<=运算符会使您超出数组的长度1。

#1


2  

In the for loop, you have:

在for循环中,您有:

i <= manchesterUnited.length

It should just be:

它应该只是:

i < manchesterUnited.length

#2


0  

You need to change this

你需要改变它

     for(var i = 0; i <= manchesterUnited.length; i++){
           totalSalary = manchesterUnited[i].salary + totalSalary;
     }

To this

      for(var i = 0; i < manchesterUnited.length; i++){
            totalSalary = manchesterUnited[i].salary + totalSalary;
      }`

The reason being that the <= operator causes you to pass beyond the length of your array by 1.

原因是<=运算符会使您超出数组的长度1。