[英]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.