javascript - 为什么这个 javascript 函数返回 undefined ?

标签 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 ,该函数仍返回 undefined ?

最佳答案

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

关于javascript - 为什么这个 javascript 函数返回 undefined ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53526325/

相关文章:

function - 使用百分号作为前缀运算符名称的一部分

C++ 重载函数和函数模板 - 不同的行为?

JavaScript - 随机函数结果之间的差异

JavaScript 代码在 codepen 上运行良好,但在 fiddle 上运行不佳。无法找到

javascript - .map 不是 javascript 中的函数

javascript - 为什么我的父组件中的状态落后了一步?

javascript - 函数仅从 $(function(){ 调用一次

javascript - 如何让 child 跨度与 parent 崩溃

javascript - 如何对具有相同键的对象值求和并返回一个对象?

reactjs - Gatsby 和 Graphql - 如何按文件夹过滤 allMarkdownRemark