JavaScript:为什么array.push()追加两个对象而不是一个

时间:2016-04-26 05:44:36

标签: javascript

我是JS的新手,我的代码存在问题,我真的不明白:我尝试将一个文本值对附加到一个数组,基本上它可以工作,但不是附加一个对,它附加两对。下面是代码片段,问题出在后面的if语句中。我已经在片段中添加了评论来解释我在做什么。

 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-variable,它实际上只包含了Bill的名字。热烈欢迎任何帮助!

1 个答案:

答案 0 :(得分:0)

来自console.log的控制台中显示的输出处于活动状态。它反映了console.log调用发生后传递给console.log的对象的更改。

在将对象传递给JSON.stringify或制作数组副本之前,您可能需要console.log

console.log(playerList.slice());
console.log(standingArray.slice());