我正在创建一个轮询应用程序,该应用程序应该记录用户的ip,以及他们投票的时间以及他们投票的选择。
为此,我设想为每个包含这些属性的“投票”创建一个对象,然后将该对象推入数组将非常适合我的需求。
在尝试使用将对象推入数组之前,一切都运行良好。我目前所说的数组未定义。
到底是什么情况?我尝试使用索引并为该对象设置votingArray [i],但这也产生了未定义的错误。
这是我的代码:
//Vote for the pet passed into by user
function vote(pet, time){
linkService.incrementCount(pet);
trackVote(pet, time);
res.render('vote', {
pet: pet
});
}
var votingArray = [];
function trackVote(pet, time) {
var voteObject = {
time: time,
pet: pet,
ip: req.ip
};
console.log(voteObject);
votingArray.push(voteObject);
console.log(votingArray);
}
function showResults(){
res.render('results', {
votingArray: votingArray
});
}
这是我的控制台中的错误:
(第69行是'votingArray.push(voteObject);')
Express started on http://localhost:8080; press Ctrl-C to terminate.
{ time: 1474584882143, pet: 'scout', ip: '::ffff:10.240.1.15' }
TypeError: Cannot read property 'push' of undefined
at trackVote (/home/ubuntu/workspace/Projects/projectTwo/app.js:69:14)
at vote (/home/ubuntu/workspace/Projects/projectTwo/app.js:51:6)
at /home/ubuntu/workspace/Projects/projectTwo/app.js:43:6
at Layer.handle [as handle_request] (/home/ubuntu/workspace/Projects/projectTwo/node_modules/express/lib/router/layer.js:95:5)
at next (/home/ubuntu/workspace/Projects/projectTwo/node_modules/express/lib/router/route.js:131:13)
at Route.dispatch (/home/ubuntu/workspace/Projects/projectTwo/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/ubuntu/workspace/Projects/projectTwo/node_modules/express/lib/router/layer.js:95:5)
at /home/ubuntu/workspace/Projects/projectTwo/node_modules/express/lib/router/index.js:277:22
at param (/home/ubuntu/workspace/Projects/projectTwo/node_modules/express/lib/router/index.js:349:14)
at param (/home/ubuntu/workspace/Projects/projectTwo/node_modules/express/lib/router/index.js:365:14)
编辑:
由于很多人建议我已声明但未实例化可变的“ votingArray”作为数组,并且我的代码片段并未包含我为满足这些评论和答案而必须重写的所有内容。
关于votingArray.push,我仍然遇到相同的错误。
这是我的新代码:
var votingArray = [];
//Vote for the pet passed into by user
function vote(pet, time){
linkService.incrementCount(pet);
var votingObject =
{
ip: req.ip,
pet: pet,
timecode: time
};
votingArray.push(votingObject);
res.render('vote', {
pet: pet
});
}
function showResults(){
res.render('results', {
votingArray: votingArray
});
}
最佳答案
您的变量votingArray
未初始化。如果要使其成为数组,则必须替换该行
var votingArray;
与
var votingArray = []; // Empty array instance
关于javascript - 使用array.push产生未定义,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39650135/