search

Home  >  Q&A  >  body text

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

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();

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

天蓬老师天蓬老师2903 days ago458

reply all(2)I'll reply

  • ringa_lee

    ringa_lee2017-04-10 15:12:01

    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控制台输出结果说明了每次执行完毕后的数组长度,你去点击查看时引用的数据对象还是同一个,所以都显示出来了
    

    reply
    0
  • 巴扎黑

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

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

    reply
    0
  • Cancelreply