我有一个给定的函数,除其他参数外,它还有两个可选参数,它们可能是函数。两者都必须是可选的,一个是函数,一个是 bool 值或返回 bool 值的函数。
// Obj.func(variable, String[, Object][, Boolean||Function][, Function]);
Obj.func = function(other, assorted, args, BoolOrFunc, SecondFunc) {
// execution
};
Obj.func(
[
'some',
'data'
],
'of varying types',
{
and: 'some optional arguments'
},
function() {
if(some condition) {
return true;
}
return false;
},
function() {
// do things without returning
}
);
我希望这两个函数(以及其他几个参数,如果重要的话)都是可选的,这意味着我在函数中有代码来确定用户打算使用哪些参数。
不幸的是,由于两者都可能是函数,并且可能在函数调用中直接指定,所以我不能简单地使用 typeof 或 instanceof 条件。然而,由于第一个函数,如果它存在,将总是返回一个 bool 值(而第二个函数根本不会返回),我的一个想法是检查它的返回值:
if(typeof BoolOrFunc === 'boolean'
|| (typeof BoolOrFunc === 'function' && typeof BoolOrFunc() === 'boolean')) {
// BoolOrFunc is either a boolean or a function that returns a boolean.
// Handle it as the intended argument.
} else {
// Otherwise, assume value passed as BoolOrFunc is actually SecondFunc,
// and BoolOrFunc is undefined.
}
原则上这是可行的;但是,运行 typeof BoolOrFunc() 会执行该函数,如果该函数不仅仅返回一个 bool 值,则会导致问题:也就是说,如果作为 BoolOrFunc 传递的函数是实际上 意味着 SecondFunc。 SecondFunc,在这种情况下,是一个回调函数,可以执行我不想立即执行的操作,包括 DOM 修改。
因此,我的问题是:有没有办法在不执行函数的情况下检查它是否返回?
我考虑过的一件事是调用 BoolOrFunc.toString(),然后对返回值执行正则表达式搜索,类似于……
if(typeof BoolOrFunc === 'boolean'
|| (typeof BoolOrFunc === 'function'
&& BoolOrFunc.toString().search(/return (true|false);/) !== -1)) {
// BoolOrFunc is either a boolean or contains a return string with a boolean.
// Handle it as the intended argument.
}
请注意,上面的代码可能不会像写的那样工作:我实际上并没有为它构建一个测试用例,因为,好吧,它看起来非常低效并且可能不可靠,我认为这里有人可能有更优雅的解决方案我的窘境。话虽如此,我想我会把它包括在内以供讨论。
最佳答案
Meshaal在题中做了预测:
"... one will either be a boolean or a function that returns a boolean."
"... first function, if it exists, will always return a boolean."
有了这个预测,函数就不是图灵机了,因为我们知道它会返回一些东西。肯定不能用简单的 RegExp 来完成:只是 return !0 会破坏示例。
但是如果您使用足够智能的解析器解析 function.toString() 的结果以找到所有可能的返回点,那么问题应该基本上是可以解决的。
关于javascript - 检查 JavaScript 函数是否在不执行的情况下返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25739387/
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass
为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar
这是在Ruby中设置默认值的常用方法:classQuietByDefaultdefinitialize(opts={})@verbose=opts[:verbose]endend这是一个容易落入的陷阱:classVerboseNoMatterWhatdefinitialize(opts={})@verbose=opts[:verbose]||trueendend正确的做法是:classVerboseByDefaultdefinitialize(opts={})@verbose=opts.include?(:verbose)?opts[:verbose]:trueendend编写Verb
这个问题在这里已经有了答案:Checktoseeifanarrayisalreadysorted?(8个答案)关闭9年前。我只是想知道是否有办法检查数组是否在增加?这是我的解决方案,但我正在寻找更漂亮的方法:n=-1@arr.flatten.each{|e|returnfalseife
我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re
我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)
我遵循了教程http://gettingstartedwithchef.com/,第1章。我的运行list是"run_list":["recipe[apt]","recipe[phpap]"]我的phpapRecipe默认Recipeinclude_recipe"apache2"include_recipe"build-essential"include_recipe"openssl"include_recipe"mysql::client"include_recipe"mysql::server"include_recipe"php"include_recipe"php::modul
我正在尝试用ruby中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了
我有一个包含多个键的散列和一个字符串,该字符串不包含散列中的任何键或包含一个键。h={"k1"=>"v1","k2"=>"v2","k3"=>"v3"}s="thisisanexamplestringthatmightoccurwithakeysomewhereinthestringk1(withspecialcharacterslike(^&*$#@!^&&*))"检查s是否包含h中的任何键的最佳方法是什么,如果包含,则返回它包含的键的值?例如,对于上面的h和s的例子,输出应该是v1。编辑:只有字符串是用户定义的。哈希将始终相同。 最佳答案