mirim mirim - 21 days ago 5
Javascript Question

access property in node.js

sorted = Object.keys(PLAYER_LIST).sort(function(a,b){return a.score - b.score}); // have key value
console.log(PLAYER_LIST[sorted[0]].team); // result:"A"

for(var loop=0; loop<=sorted.length; loop++) {
if(PLAYER_LIST[sorted[loop]].team == "A") { // error
some code...
}
}


When I sorting like this. console.log working well. But if sentence is not working. I receive error message. I don't know why. please help me.

if(PLAYER_LIST[sorted[loop]].team == "A") {
^

TypeError: Cannot set property 'team' of undefined

Answer

Your loop goes one step too far

for (var loop = 0; loop <= sorted.length; loop++) {
//                      ^^ here

An arrays length starts at zero when it's empty, and is 1 if the array contains one item.

If you have an array

var array = ['a']

arrays are zero based, so the first and only item is array[0], and the length is 1

When you iterate and you go all the way to the arrays length, you go one index too much, and you end up trying to get array[1], which doesn't exist.

What you wanted was

for (var loop = 0; loop < sorted.length; loop++) {...
Comments