我有:
- 字典(
函数
)将字符串前缀映射到函数 - 返回映射到字符串的函数的函数 (
get()
) - 一个函数 (
check()
),它通过调用get()
并使用将其转换为 bool 值来检查是否有映射到字符串的函数! !
.
当我在 functions
中使用键调用 get()
时,我希望 check()
返回 true
;但是,它返回 false
。我在 get()
中执行字典查找并在两个函数中打印结果的类型。这是奇怪的部分。只有在get()
中类型是function
;在 check()
中,它是 undefined
。显然,当我返回该函数时,该函数会被删除或发生其他情况。如何使 check()
准确?
这是我的简化代码:
var someObject = {
functions: {
"a": function () { return 0; },
"b": function () { return 1; }
},
get: ( function ( someVariable ) {
Object.keys( this.functions ).forEach( ( function ( functionKey ) {
if ( someVariable.startsWith( functionKey ) ) {
console.log( typeof this.functions[ functionKey ] );
return this.functions[ functionKey];
}
} ).bind( this ) );
} ),
check: function ( stringToCheck ) {
var returnedFunction = this.get( stringToCheck );
console.log( typeof returnedFunction );
return !!returnedFunction;
}
}
$( document ).ready( function () {
someObject.check( "a" );
} );
运行这段代码会产生这样的结果:
"function"
"undefined"
在控制台中。
最佳答案
这是因为 forEach
没有在 return
语句上提前中断/短路(它继续进行下一次迭代,然后是 get
函数返回 undefined
)。您可以重写循环以允许中断(例如,使用简单的 for-loop
),或者您可以在循环后返回值,例如:
var someObject = {
functions: {
"a": function () { return 0; },
"b": function () { return 1; }
},
get: ( function ( someVariable ) {
var func;
Object.keys( this.functions ).forEach( ( function ( functionKey ) {
if ( someVariable.startsWith( functionKey ) ) {
console.log( typeof this.functions[ functionKey ] );
func = this.functions[ functionKey];
}
} ).bind( this ) );
return func;
} ),
check: function ( stringToCheck ) {
var returnedFunction = this.get( stringToCheck );
console.log( typeof returnedFunction );
return !!returnedFunction;
}
}
关于javascript - 返回时函数变为未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31756107/