为什么此javascript函数返回undefined?

时间:2018-11-28 18:58:50

标签: javascript reactjs function ecmascript-6

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); 
    }

当我这样执行控制台日志时:

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

我得到这样的日志输出:

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

即使Number(idTovalue[id])的值恢复为正常值69,为什么函数仍返回未定义状态?

1 个答案:

答案 0 :(得分:2)

什么也没有返回,因为forEach回调是一个单独的方法。我删除了对.forEach的调用,并将其替换为一个for of循环,该循环维护了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); 
    }