【问题标题】:Why is this javascript function returning undefined ?为什么这个 javascript 函数返回 undefined ?
【发布时间】:2019-04-30 18:24:25
【问题描述】:
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]) evalues 为正常值 69 ,函数仍返回 undefined ?

【问题讨论】:

  • 因为return 语句在forEach 回调内部,而不是在getLowerUpperBoundFromValue 内部。从“内部”函数返回不会神奇地从外部函数返回。简单示例:function outer() { function inner() { return 'inner'; }; inner(); return 'outer'; }; outer(); 返回"outer"
  • @Solo: forEach 不返回任何东西,所以这也无济于事。
  • forEach 用于在数组中查找索引/条目是错误的。你应该使用find()

标签: javascript reactjs function ecmascript-6


【解决方案1】:

没有返回,因为 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); 
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-21
    • 2018-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-11
    相关资源
    最近更新 更多