如何从函数中返回变量

时间:2021-05-24 13:13:06

标签: javascript scope

我知道这是一个范围问题。出于某种原因,我无法让函数 caculateValue 返回“oplossing”的值。 console.log (oplossing + "oplossing-0"); console.log (oplossing + "oplossing-1");并且可以读取值。它停在: console.log (oplossing + "oplossing-2");从这里我得到一个错误。 谁知道这个问题的解决方案。

export function caculateValue(nieuwVerbruik, nummer) {

    let database = firebase.database();
    let monthRef = database.ref("eindemaand");

    monthRef.orderByChild("dateID").limitToLast(1).once('value', function (snapshot) {

        snapshot.forEach(function (childSnapshot) {

            // this is the whole object
            console.log(snapshot.val());

            //these are the various property values
            let dateID = childSnapshot.child("dateID").val();

            let oldmeterstandVerEL = childSnapshot.child("meterstandVerEL").val();
            let oldmeterstandVerEH = childSnapshot.child("meterstandVerEH").val();
            let oldmeterstandTerEL = childSnapshot.child("meterstandTerEL").val();
            let oldmeterstandTerEH = childSnapshot.child("meterstandTerEH").val();
            let oldmeterstandVerGas = childSnapshot.child("meterstandVerGas").val();
            let oldmeterstandVerWat = childSnapshot.child("meterstandVerWat").val();
            let oldmeterstandZonPan = childSnapshot.child("meterstandZonPan").val();

            let old = [oldmeterstandVerEL, oldmeterstandVerEH, oldmeterstandTerEL, oldmeterstandTerEH, oldmeterstandVerGas, oldmeterstandVerWat, oldmeterstandZonPan];

            window.oplossing = nieuwVerbruik - old[nummer];
            //globalThis.oplossing = nieuwVerbruik - old[nummer];

            // this is going well
            console.log(nummer);
            // this is going well
            console.log(nieuwVerbruik);
            // this is going well
            console.log(oplossing + " oplossing-0");
        });
        //this is going well
        console.log(oplossing + " oplossing-1");        
    });
    // At 'window.oplossing' and at 'globalThis.oplossing' it gives the error message 'Uncaught refferenceError: solution not Defined'
    console.log(oplossing + " oplossing-2");
}

0 个答案:

没有答案