简体   繁体   中英

Cannot read property of array

In my app.js, I have the following:

post.find({'global': true}).sort('date').exec(function(err, data) {
  for (var i = 0; i <= data.length; i++) {
    console.log(data[i].email);
    //socket.emit('Post', {name: data[i].name, cont: data[i].cont, date: data[i].date});
  }
});

When I use

console.log(data[i]);

I get my data in the form of

{name: blah, cont: blah, email: blah, etc}

But when i try emitting the data

data[i].attribute

I get the error

TypeError: Cannot read property 'attribute' of undefined

I know the data is there, as I am able to log it in the console. Why can't I access the specific attribute of the array? Any ideas?

It might be because of how you're using your loop. Your logic with <= will causes the loop to run one extra time, therefore accessing an array value that doesn't exist. This is a case of what's happening:

var data = [{ foo: 'bar1' }, { foo: 'bar2' }];
for (var i = 0; i <= data.length; i++) {
  console.log(data[i].foo);
}

The loop will run three times instead of twice, causing this to happen:

console.log(data[0].foo); // bar1
console.log(data[1].foo); // bar2
console.log(data[2].foo); // TypeError: Cannot read property 'foo' of undefined

To fix this, change your loop to for (var i = 0; i < data.length; i++) .

Also, a debugging tip: you should try using output when inspecting errors like yours, even if data was an array with a length of a thousand, the error would still only be thrown on the last iteration, and with socket.emit() it would appear as if the loop only ran once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM