简体   繁体   English

无法读取数组的属性

[英]Cannot read property of array

In my app.js, I have the following: 在我的app.js中,我有以下内容:

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: 该循环将运行3次而不是2次,从而导致这种情况发生:

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++) . 要解决此问题,请将您的循环更改为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. 另外,这是一个调试提示:在检查类似您的错误时,您应该尝试使用输出,即使data是长度为一千的数组,该错误仍然只会在上一次迭代时抛出,并使用socket.emit()看起来就像循环只运行一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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