javascript - jquery 循环给全局变量数组 push 对象,为啥数组第一次打印出来就包含了全部要 push 的对象?
天蓬老师
天蓬老师 2017-04-10 15:10:01
0
2
460
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 里面的打印结果很奇怪。

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(2)
左手右手慢动作
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控制台输出结果说明了每次执行完毕后的数组长度,你去点击查看时引用的数据对象还是同一个,所以都显示出来了
巴扎黑

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template