2016-04-26 8 views
0

私はJSにはかなり新しく、私のコードには本当に理解できない問題があります。基本的には機能しますが、1つのペアを追加する代わりに、2つのペアが追加されます。以下はコードスニペットであり、問​​題は後者のif文にあります。私はスニペットに私が何をしているのかを説明するコメントを追加しました。JavaScript:なぜarray.push()が1つではなく2つのオブジェクトを追加するのですか?

players.addResult = function(result){ 

//result-argument contains results of games, like: Object {0: "4-2", 1: "5-3", 2: "7-1"} 


    var playerList = [];   
    var standingArray = []; 

    resultLen = Object.keys(result).length; 

    //loop iterates thru results by index 
    for (var x=0; x < resultLen; x++) { 
     var newResult = result[x]; 
     newResult = newResult.split("-"); 

     if (newResult[0] > newResult[1]) { 

      //the next line retrieves the name of a winning player from another array 
      playerVal = players.pairs[x].player1; 
      playerVal = playerVal.text; 
      console.log(playerVal); //Output of this: Bill 
      value = playerList.indexOf(playerVal); // Checks if the player already exists on the standings, returns -1 if false. 

      if (value === -1) { 

      /*if the player gets his first points, his name and earned 
      points are added on to the standingArray. And the next line of code is the 
      interesting one, because I am expecting to have an array with 
      index, name of the winner and points. Like this: 
      Object 0 name:"Bill" points:2. But instead of that, there are two     
      objects on the array, one for both players: 
      [Object] 
      0: Object 
      name: "Bill" 
      points: 2 
      __proto__: Object 
      1: Object 
      name: "Greg" 
      points: 2 
      __proto__: Object 
      length: 2 
      __proto__: Array[0]*/ 

       standingArray.push({name: playerVal, points: 2}) 

       playerList.push(playerVal); //this is for keeping on track that player is now on the standingArray 

       console.log(playerVal); 
       console.log(playerList); 
       console.log(standingArray); 
      } 
      else { 
       console.log("else"); 
      }    
     console.log(playerList); 
     console.log(standingArray); 

そこで質問は、JSはGregの名前を取得する方法ということである - 私はplayerVal変数をチェックして、それは本当に唯一のビルの名前が含まれています。どんな援助も大歓迎です!

+0

チェック 'players.pairs'配列、多分グレッグは1つの試合に勝って、ビルは別の勝 –

答えて

0

コンソールに表示される出力はconsole.logです。 console.log呼び出しが発生した後に、console.logに渡されたオブジェクトに対する変更が反映されます。

あなたはconsole.logにオブジェクトを渡す前にJSON.stringifyにしたいか、配列のコピーを作成することがあります

console.log(playerList.slice()); 
console.log(standingArray.slice()); 
関連する問題