为什么这个javascript函数返回undefined?(Why is this javascript function returning undefined? [duplicate])

编程入门 行业动态 更新时间:2024-10-26 19:30:26
为什么这个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 answers

Why 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.

更多推荐

本文发布于:2023-08-06 15:18:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1451148.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   undefined   javascript   duplicate   returning

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!