![](/img/trans.png)
[英]Why is console.log() logging undefined when my function seems to be returning the right answer?
[英]Why is my console.log returning undefined in JavaScript?
我需要訪問我的局部變量,我嘗試過這種方式。 但到目前為止還沒有運氣,任何幫助或建議將不勝感激。
我console.log(sum1)
它返回undefined
var sum1;
const q = query(collection(db, "users"),where("selected", "==", "Gasto"), where("moneda", "==", "$"));
const unsubscribe = onSnapshot(q,(querySnapshot) => {
const dolarCurrency = [];
const months =[];
querySnapshot.forEach((doc) =>{
dolarCurrency.push(doc.data().cantidad);
months.push(doc.data().fecha)
})
const hash = months.map((Day) => ({ Day }));
const hashDolar = dolarCurrency.map(( Amount ) => ({ Amount }))
const output = hash.map(({Day},i) => ({Day, ...hashDolar[i]}));
sum1 = output.reduce((acc, cur)=> {
const found = acc.find(val => val.Day === cur.Day)
if(found){
found.Amount+=Number(cur.Amount)
}
else{
acc.push({...cur, Amount: Number(cur.Amount)})
}
return acc
}, [])
return sum1
})
console.log(sum1)
您在unsubscribe
function 之外調用 console.log,這是設置sum1
的值的地方。 這將更容易查看您的代碼格式是否更好(請始終格式化您的代碼)。 這是它的要點:
var sum1;
const unsubscribe = onSnapshot(q, (querySnapshot) => {
// sum1 gets set in here eventually (keyword "eventually")
};
console.log(sum1); // value is undefined until the function above gets invoked
在嘗試記錄值之前,您需要確保調用了 function。 另一種選擇是將日志語句移動到 function 中。
var sum1;
const unsubscribe = onSnapshot(q, (querySnapshot) => {
sum1 = ...;
console.log(sum1);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.