gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 23:07:43 28 4
gpt4 key购买 nike

我是 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com