预定义我要创建的变量类型
我敢打赌,通过从 jc.half = jc.half();
中删除该部分,以下情况会更有效。我只是不太确定怎么做。
jc.half = function(){
if(jc.singlerow){
return jc.total
}else{
return jc.total / 2;
}
}
// returns function()
jc.half = jc.half();
// returns the right integer
我正在寻找一个执行类似操作的解决方案:
jc.half = returnInteger(function(){
if(jc.singlerow){
return jc.total
}else{
return jc.total / 2;
}
})
// returns the right integer
I bet the following situation can be more efficient by removing the part from jc.half = jc.half();
. I'm just not quite sure how.
jc.half = function(){
if(jc.singlerow){
return jc.total
}else{
return jc.total / 2;
}
}
// returns function()
jc.half = jc.half();
// returns the right integer
I'm looking for a solution that does something like this:
jc.half = returnInteger(function(){
if(jc.singlerow){
return jc.total
}else{
return jc.total / 2;
}
})
// returns the right integer
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
诀窍在于,当您得到一个以解析器可以知道它是表达式中的值的方式开始的函数声明时,那么函数定义是表达式的一部分,您可以这样使用它并调用该函数。实际上,在这样的作业的右侧,甚至没有必要使用“包装”括号,但我这样做只是出于习惯,也是为了在阅读代码时让自己清楚。
当然,在这种情况下,您可以完全省略该函数。
编辑 - 一位有用的评论者指出您提到您需要一个整数;如果是这样,您需要对结果调用
Math.floor()
或Math.round()
。或者你可以“作弊”一点,这样做:The trick is that when you've got a function declaration that starts in such a way that the parser can tell that it's meant to be a value in an expression, then the function definition is part of the expression, and you can use it that way and invoke the function. Really, on the right side of an assignment like that, it's not even necessary to use the "wrapper" parentheses, but I do it just out of habit and to keep things clear to myself when reading code.
Of course in this case you could omit the function entirely.
edit — a helpful commenter notes that you mention you need an integer; if so, you'll want to call
Math.floor()
orMath.round()
on your result. Or you could "cheat" a little and do this:这不是获得正确类型的问题...您定义了函数,但没有执行它!您可以使其自动执行:
尽管如此,是否有必要具有该功能?
It's not a matter of getting the right type... you defined the function, but didn't execute it! You can make it self executing:
Although, is it even necessary to have the function?
目前尚不清楚为什么需要一个函数。
It isn't clear why you need a function.