为什么这个javascript函数返回undefined?(Why is this javascript function returning undefined? [duplicate])
这个问题在这里已经有了答案:
Javascript函数无法返回元素 2的答案 Object.keys forEach返回未定义的 2个答案 函数forEach返回未定义,即使返回语句 5的答案 ES6类方法不会在forEach循环内返回任何内容 2个答案 为什么在使用return语句 4回答 时forEach返回undefined为什么这个函数返回undefined? 它在函数内部有一个值,但是一旦我尝试将它赋值给一个新变量,它就会返回为undefined。
function getLookupDefault(lookupModel) { Object.keys(lookupModel.LookupValues).forEach(function (key) { if (lookupModel.LookupValues[key].IsDefault == true) { test = lookupModel.LookupValues[key].Name; console.log("test: " + test); return test; } }) }; var tst = getLookupDefault(model.LookupValuesDelimiter); console.log("tst: " + tst);编辑:谢谢。 来自C#,这对我来说并不明显。 我编辑了这个代码,它能正常工作。
function getLookupDefault(lookupModel) { for (var key in Object.keys(lookupModel.LookupValues)) { if (lookupModel.LookupValues[key].IsDefault == true) { test = lookupModel.LookupValues[key].Name; console.log("test: " + test); return test; } } }This question already has an answer here:
Javascript function fails to return element 2 answers Object.keys forEach returns undefined 2 answers Function with forEach returns undefined even with return statement 5 answers ES6 class methods not returning anything inside forEach loop 2 answers Why does this forEach return undefined when using a return statement 4 answersWhy is this function returning undefined? It has a value inside the function, but once I try to assign it to a new variable, it comes back as undefined.
function getLookupDefault(lookupModel) { Object.keys(lookupModel.LookupValues).forEach(function (key) { if (lookupModel.LookupValues[key].IsDefault == true) { test = lookupModel.LookupValues[key].Name; console.log("test: " + test); return test; } }) }; var tst = getLookupDefault(model.LookupValuesDelimiter); console.log("tst: " + tst);Edit: Thank you. Coming from c#, this was not obvious to me. I have edited the code to this and it works correctly.
function getLookupDefault(lookupModel) { for (var key in Object.keys(lookupModel.LookupValues)) { if (lookupModel.LookupValues[key].IsDefault == true) { test = lookupModel.LookupValues[key].Name; console.log("test: " + test); return test; } } }最满意答案
你在那里的返回语句没有向外部函数返回一个值,它只返回一个值给forEach调用的内部函数。
That return statement you have in there doesn't return a value to the outer function, it only returns a value to the inner function called by forEach.
更多推荐
发布评论