首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JavaScript:为什么array.push()追加两个对象而不是一个对象

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

Stack Overflow用户
提问于 2016-04-26 13:44:36
回答 1查看 67关注 0票数 0

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

代码语言:javascript
复制
 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变量,它实际上只包含Bill的名字。我们热诚欢迎您的帮助!

EN

回答 1

Stack Overflow用户

发布于 2016-04-26 13:51:35

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

您可能希望在将对象传递给console.log之前执行JSON.stringify操作,或者创建数组的副本:

代码语言:javascript
复制
console.log(playerList.slice());
console.log(standingArray.slice());
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36856180

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档