簡體   English   中英

JavaScript:為什么array.push()追加兩個對象而不是一個

[英]JavaScript: why array.push() appends two objects instead of one

我對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的名字。 熱烈歡迎任何幫助!

console.log出現在控制台中的輸出仍然有效。 它反映了在進行console.log調用之后傳遞給console.log的對象的更改。

您可能需要JSON.stringify傳遞給console.log或復制Array:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM