Javascript函数始终返回null [英] Javascript function always returns null
问题描述
我是JavaScript世界的新手。我怀疑返回语句在JavaScript中是如何工作的。
I am newbie to the JavaScript world. I have a doubt how the return statement works in JavaScript.
我要做的是让一个函数传递一个参数 param
并查看 param
是否与 exampleData
对象的键匹配。如果匹配发现我想返回值并打破每个函数的循环也打破了我不想在每个函数下执行任何其他语句的函数。如果未找到匹配项,则该函数必须返回null。但是目前函数总是返回null值。
What I am trying to do is to have a function pass one arguments param
and looking whether the param
match the key of the exampleData
object. If match found I want to return the value and break the looping of each function also break the function I don't want to execute any other statement under the each function. If no match found the function must return null. But currently the function always return null value.
function exampleFunction(param){
$.each(exampleData, function (key, value) {
if(key == param){
return value;
}
});
return null;
}
任何对此的见解都将受到高度赞赏。谢谢。
Any insight into this would highly be appreciated. Thank you.
推荐答案
您的示例似乎不需要循环。那个并且从循环委托中返回并没有为你做任何事情。
Your example doesn't seem to need a loop. That and returning from the loop-delegate doesn't do anything for you.
你可以使用 在
运算符中。
You can test if a key appears in an object using the in
operator.
function exampleFunction(param){
return param in exampleData ? exampleData[param] : null;
}
这篇关于Javascript函数始终返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!