簡體   English   中英

從另一個 function 調用 function 時獲取未定義的變量

[英]Getting undefined variable when calling function from another function

抓着我的頭。 嘗試調用 function 時出現未定義的錯誤。 問題是,當我打印到控制台時,我可以清楚地看到正在傳遞的數據。

未捕獲的類型錯誤:convos 未定義

功能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

我相信您需要在 showConversation() 的括號內輸入一些內容。

您正在將 convos 分配給 myconvo,但 myconvo 不存在,因為您沒有將其作為參數輸入(括號中的值)。

您的第一個錯誤是您沒有將任何 arguments 傳遞給 function。

您的第二個錯誤是 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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM