从另一个函数调用函数时获取未定义的变量



挠我的头。我在尝试调用函数时遇到了一个未定义的错误。问题是,当我打印到控制台时,我可以清楚地看到正在传递的数据。

未捕获类型错误:卷积是未定义的

功能1

function fetchConversation(userID){
//loop through 
usersms.forEach(function (sms,counter) {
//get userid from  iteration
var userid_loop = sms.details[0].user.id;
//only display convo from specific user
if(userid_loop === userID){
//get all messages from this one user
var conversation = sms.details;
//transfer conversation to next function to display
showConversation(conversation);
//
}
//
});
}

功能2

function showConversation(myconvo){

var convos = myconvo;

//iterate and append conversion
convos.forEach(function (msg,counter) {

console.log(msg.message);//prints all messages in the log

});
}
showConversation()//Uncaught TypeError: convos is undefined

我认为您需要在showConversion((的括号内输入一些内容。

您正在将卷积分配给myconvo,但myconvo不存在,因为您没有将其作为参数(括号中的值(输入。

您的第一个错误是没有向函数传递任何参数。

您的第二个错误是msg.message不存在——它只是msg本身。

此外,在这种情况下,计数器是不必要的。

function showConversation(myconvo) {
var convos = myconvo;
//iterate and append conversion
convos.forEach(function(msg) {
console.log(msg); //prints all messages in the log
});
}
showConversation(["element1", "element2"])

这里也有一个错误:

function fetchConversation(userID){
//loop through
usersms.forEach(function (sms,counter) {
//get userid from  iteration
var userid_loop = sms.details[0].user.id;
//only display convo from specific user
if(userid_loop === userID){
//get all messages from this one user
var conversation = sms.details; //actually gets the details of the element it is iterating through, not all of them
//transfer conversation to next function to display
showConversation(conversation); //sends the details one by one for each iteration
//
}
//
});
}

修复:

function fetchConversation(userID){
var conversation=[]
//loop through
usersms.forEach(function (sms,counter) {
//get userid from  iteration
var userid_loop = sms.details[0].user.id;
//only display convo from specific user
if(userid_loop === userID){
//get all messages from this one user
conversation.push(sms.details);
}
});
//transfer conversation to next function to display
showConversation(conversation);
}

最新更新