代码之家  ›  专栏  ›  技术社区  ›  Natesh bhat

为什么这个javascript函数返回未定义的值?

  •  0
  • Natesh bhat  · 技术社区  · 7 年前
    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 回复  |  直到 7 年前
        1
  •  2
  •   Smarticles101    7 年前

    没有返回任何内容,因为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); 
        }
    
    推荐文章