recherche

Maison  >  Questions et réponses  >  le corps du texte

javascript - jquery 循环给全局变量数组 push 对象,为啥数组第一次打印出来就包含了全部要 push 的对象?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

<code>var goal = [];

var localGoal = [

{a:'a', b:'b', c:'c'},

{a:'e', b:'f', c:'g'},

{a:'h', b:'i', c:'j'}];

 

function add () {      

    $.each(localGoal, function(index, val) {

            var temp = {};

            temp.tempa = val.a;

            temp.tempb = val.b;

            temp.tempc = val.c;

            goal.push(temp);   

            console.log(goal);             

    });

}

 

var main = function () {

    add();

}

 

main();

</code>

Chrome 的 console 里面的打印结果很奇怪。

天蓬老师天蓬老师2906 Il y a quelques jours462

répondre à tous(2)je répondrai

  • ringa_lee

    ringa_lee2017-04-10 15:12:01

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    <code>var goal = [];

    var localGoal = [

    {a:'a', b:'b', c:'c'},

    {a:'e', b:'f', c:'g'},

    {a:'h', b:'i', c:'j'}];

     

    function add () {      

        $.each(localGoal, function(index, val) {

                var temp = {};

                temp.tempa = val.a;

                temp.tempb = val.b;

                temp.tempc = val.c;

                goal.push(temp);   

                console.log(index+":"+"result");

                for(var u=0;u<goal.length;u++){

                    console.log(goal[u]);        

                }

                //console.log(goal.toString());             

        });

    }

     

    var main = function () {

        add();

    }

     

    main();

     

    //console.log(goal.toString());  chrome控制台输出结果说明了每次执行完毕后的数组长度,你去点击查看时引用的数据对象还是同一个,所以都显示出来了

    </code>

    répondre
    0
  • 巴扎黑

    巴扎黑2017-04-10 15:12:01

    http://stackoverflow.com/questions/24175017/google-chrome-console-log-...

    répondre
    0
  • Annulerrépondre