在推送对象时,Array.push()使所有元素都相同

pat*_*pat 14 javascript node.js

我是节点和javascript的新手,并且一直在敲打以下内容.我创建了一个对象如下:

var Subscriber = {
'userID': String,
'email': String,
'name': String,
'stage': String,
'poster': Boolean,
'canEmail': Boolean,
'stage': String, }
Run Code Online (Sandbox Code Playgroud)

我有一个函数,我查询mongodb,并循环结果,尝试加载一组订阅者,我已声明为:

var s = Subscriber;
var subscribers = [];
Run Code Online (Sandbox Code Playgroud)

循环看起来像这样:

//load array of users that are subscribed to the group
        async.forEach(g.subscribers, function(item, callback) {     
            //load user document for this user
            User.findOne({ _id: item}, function(err, u) {
                if(!err && u) {                 
                    //var s = new Subscriber();
                    console.log('Sub load, found user %s, building array item', u.email);
                    console.log('Subs @ loop start');
                    console.log(util.inspect(subscribers));

                    console.log('Heres foo: ' + util.inspect(foo));


                    s.userID = u._id;
                    s.email = u.email;
                    s.name = u.firstName + ' ' + u.lastName;
                    s.stage = u.stage;
                    s.poster = false; //we're just loading subscribers at this point'
                    if(s.stage != 'new') s.canEmail = true;

                    //push new subscriber onto the array
                    console.log('Pushing ' + util.inspect(s));
                    subscribers.push(s);

                    console.log('At end ' + util.inspect(subscribers));

                    foo.push(s.email);
                    console.log('Heres foo now: ' + util.inspect(foo));

                    callback(null, item);
                }
Run Code Online (Sandbox Code Playgroud)

每次调用subscriber.push(s)之后,数组都有正确数量的元素,但是所有元素都匹配s的最后一个值,就像这样(从数据库中提取两个不同的用户):

[ { userID: 4fc53a71163006ed0f000002,
email: 'test@test.com',
name: 'undefined undefined',
stage: 'new',
poster: false,
canEmail: true },
  { userID: 4fc53a71163006ed0f000002,
email: 'test@test.com',
name: 'undefined undefined',
stage: 'new',
poster: false,
canEmail: true } ]
Run Code Online (Sandbox Code Playgroud)

推动单个元素而不是整个对象似乎没问题.我添加了"foo"数组作为测试,它工作正常:

Heres foo now: [ 'email1@foo.com', 'test@test.com' ]
Run Code Online (Sandbox Code Playgroud)

这里发生了什么?!?!??!

KAR*_*ván 20

问题不push在于Array.prototype你的绑定方法.您正在块s中的每个迭代中修改相同的对象,async.foreach该实际上是与先前定义的对象相同的对象Subscriber.

首先,您应该将s变量的声明移动到foreach块.

而且如果你想用默认值创建一个对象,它应该是a function,它返回一个新对象:

function Subscriber() {
  return {
    'userID':   '',
    'email':    '',
    'name':     '',
    'stage':    '',
    'poster':   false,
    'canEmail': false,
    'stage':    ''
  };
};
Run Code Online (Sandbox Code Playgroud)

然后你可以Subscriber像这样实例化一个对象:

var s = Subscriber();
Run Code Online (Sandbox Code Playgroud)

有关更多说明,请参阅此答案MDN上的闭包.