为什么此javascript函数返回undefined? [英] Why is this javascript function returning undefined ?

查看:81
本文介绍了为什么此javascript函数返回undefined?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

let getLowerUpperBoundFromValue=(bound , idToValue)=>{
        // Returns the value of the variable previously generated if "value" is a variable name  or return "value" if its a number . 
        // bound :  can be a direct integer or a variable name. 
        // idToValue : contains the id to value mapping which must contain a variable whose name must be equal to 'bound' parameter if its a variable name . 

        if(isNaN(Number(bound)))
        {
            Object.entries(idToVarStatesGlobal).forEach(idStatePair=>{
                let id= idStatePair[0] , varState = idStatePair[1] ; 
                if(varState.name===bound){
                    console.log("check now Returning idTovalue[id]" , idToValue , id , idToValue[id] , Number(idToValue[id]));
                    return Number(idToValue[id]) ; 
                }
            })
        }
        else return Number(bound); 
    }

当我做这样的控制台日志时:

When I do a console log like this :

console.log('check now: ' , getLowerUpperBoundFromValue(varState.lowerbound , idToValue)) ; 

我得到这样的日志输出:

I get the log output like this :

check now Returning idTovalue[id] {PSfCL5hBm: 69} PSfCL5hBm 69 69
inputGeneration.js:99 check now:  undefined

即使 Number(idTovalue [id])的值仍为正常值69

Why is the function returning undefined even though the Number(idTovalue[id]) evalues to a normal value 69 ?

推荐答案

什么也没有返回,因为forEach回调是一个单独的方法。我删除了对 .forEach 的调用,并将其替换为 for的循环,该循环维护了返回

Nothing is returning because the forEach callback is a seperate method. I removed the call to .forEach and replaced it with a for of loop which maintains scope for the return

let getLowerUpperBoundFromValue=(bound , idToValue)=>{
        // Returns the value of the variable previously generated if "value" is a variable name  or return "value" if its a number . 
        // bound :  can be a direct integer or a variable name. 
        // idToValue : contains the id to value mapping which must contain a variable whose name must be equal to 'bound' parameter if its a variable name . 

        if(isNaN(Number(bound)))
        {
            for (let idStatePair of Object.entries(idToVarStatesGlobal)) {
                let id= idStatePair[0] , varState = idStatePair[1] ; 
                if(varState.name===bound){
                    console.log("check now Returning idTovalue[id]" , idToValue , id , idToValue[id] , Number(idToValue[id]));
                    return Number(idToValue[id]) ; 
                }
            }
        }
        else return Number(bound); 
    }

这篇关于为什么此javascript函数返回undefined?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆