2016-11-13 55 views
-1
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... 
    } 
    } 

當我這樣排序。 console.log運行良好。但是如果判決不起作用。我收到錯誤消息。我不知道爲什麼。請幫幫我。在node.js訪問屬性

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

TypeError: Cannot set property 'team' of undefined 

回答

0

你的循環進了一步太遠

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

的數組長度以零開始的時候它是空的,並且是1如果數組包含一個項目。

如果你有一個數組

var array = ['a'] 

數組是從零開始的,所以第一個也是唯一產品array[0],長度爲1

當你迭代和你一直走下去的數組長度,你過多地去了一個索引,並且你最終試圖得到array[1],這不存在。

你想要的是什麼

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

太感謝你了!!!!!!! – firepunch

+0

我可怕的錯誤.. :( – firepunch