[英]Array gives me 'Cannot read property of undefined' but console.logs show otherwhise
I'm trying to do a method in which i process an array of messages, every message haves an id of the user sending the message and the content of the meesage itself. 我正在尝试执行一种方法,在该方法中我处理一系列消息,每个消息都有发送消息的用户的ID和消息本身的内容。
Once i get the array, i try to separate the messages by the user who send it (In order to style the messages according to the users later on). 一旦获得数组,我将尝试按发送该数组的用户分开消息(以便稍后根据用户设置消息样式)。
I attempt to do this with a for loop to read the array, and an if to check if the logged user send such message or not. 我尝试使用for循环来执行此操作,以读取该数组,并使用if来检查登录用户是否发送了此类消息。
The problem pops up when i want to read who send the message. 当我想阅读发送消息的人时,问题弹出。
At first i thought "i may be writing the sentence wrong", so i used some consol.logs to see what was wrong. 起初我以为“我可能把句子写错了”,所以我使用了一些consol.logs来查看出了什么问题。 And i got an interesting situation going on: The variable shows correctly on the console, but i get an error once i want to evaluate on the if .
而且我遇到了一个有趣的情况:变量在控制台上正确显示,但是一旦我想对if求值,我就会报错。
Here's the JavaScript code i'm running 这是我正在运行的JavaScript代码
function processMeesages(allMessages) {
for (var i = 0; i <= allMessages.length; i++) {
console.log('allMessages[' + i + '].userMsg', allMessages[i].userMsg)
//Message from the logged user
if (allMessages[i].userMsg == user.id) {
chatMessages += '<div class="row ">' +
' <div class="col col-10 "></div>' +
' <div class="col card owner-container">' +
' <div class="item item-text-wrap owner">' +
allMessages[i].contenido +
' </div>' +
' </div>' +
' </div>';
}
//Messages from the other user
else {
chatMessages += '<div class="row ">' +
' <div class="col card message-container">' +
' <div class="item item-text-wrap message">' +
allMessages[i].contenido +
' </div>' +
' </div>' +
' <div class="col col-10 "></div>' +
' </div>';
}
}
//Once the for loop ends (What's down didn't show up on the console)
$rootScope.chatMessages = chatMessages;
console.log('chatMessages', chatMessages)
console.log('rootscopeChatMessages', $rootScope.chatMessages)
}
Here's an image with what i get in the console and what the array haves inside (I put some labels on the picture) 这是一张图像,其中包含我在控制台中获得的内容以及数组内部所包含的内容(我在图片上贴了一些标签)
Seems like you are looping more than required. 好像您循环的次数超过了要求。 Your array only has two elements but your for loop tries to loop over 3 times, hence giving that access error because
allMessages[2]
is undefined. 您的数组只有两个元素,但是您的for循环尝试循环3次以上,因此由于
allMessages[2]
未定义,因此会出现该访问错误。
function processMeesages(allMessages) {
for (var i = 0; i < allMessages.length; i++) {
console.log('allMessages[' + i + '].userMsg', allMessages[i].userMsg)
.
.
.
.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.