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

标签 javascript node.js

我是 node 和 javascript 的新手,并且一直在努力解决以下问题。我创建了一个对象如下:

var Subscriber = {
'userID': String,
'email': String,
'name': String,
'stage': String,
'poster': Boolean,
'canEmail': Boolean,
'stage': String, }

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

var s = Subscriber;
var subscribers = [];

循环如下所示:

//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);
                }

在每次调用subscribers.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 } ]

推送 s 的单个元素而不是整个对象似乎没问题。我添加了“foo”数组作为测试,它工作正常:

Heres foo now: [ 'email1@foo.com', 'test@test.com' ]

这是怎么回事?!?!??!

最佳答案

问题不在于 Array.prototypepush 方法,而在于您的绑定(bind)。 您在 async.foreach block 中的每次迭代中都修改相同的 s 对象,这实际上是与先前定义的 Subscriber 相同的对象。

首先,您应该将 s 变量的声明移动到 foreach block 中。

而且如果你想创建一个具有默认值的对象,它应该是一个函数,它返回一个新对象:

function Subscriber() {
  return {
    'userID':   '',
    'email':    '',
    'name':     '',
    'stage':    '',
    'poster':   false,
    'canEmail': false,
    'stage':    ''
  };
};

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

var s = Subscriber();

this answerClosures on MDN更多解释。

关于javascript - Array.push() 使所有元素在推送对象时都相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10932584/

相关文章:

javascript - 从 URL 中删除 anchor 标记

javascript - 为什么 JavaScript NodeList 是不可变的?

javascript - 如何在 URL 构建中转义 & 运算符

node.js - AWS-serverless-express 从不使用 promise 解决

node.js - TypeError : assert. isNotEmpty 不是带有 chai 断言的函数

javascript - 如何从 discord.js 中提取消息数据?

node.js - Mongoose :检测插入的文档是否重复,如果是,则返回现有文档

javascript - 抓取网页: Getting search results from a webpage

javascript - 如何在 Plottable.js/D3.js 制作的 Piechart 中启用 qtip2

node.js - 处理浏览器重新加载 socket.io