我需要在函数的参数内执行指定的操作。我见过一次这样做,但我不记得语法了。
最佳答案
原始答案 请参阅下面的更新答案
...to perform the specified operations within the argumnts of a function...
我不知道“内部”是什么意思。 :-)
但这也许就是您正在寻找的:
function foo(num) {
return Math.round(Math.rand() * num);
}
更多阅读:
- MDN 的页面
Math
object
更新答案
在下面回复您的评论:
I need the math to happen where it says "num" :).
你不能在 JavaScript 中做到这一点。声明函数时,您可以在上面的 num
位置放置形式参数的名称。那里不能有表达式。
不过,您可以这样做:
function foo(num) {
num = Math.round(Math.rand() * num);
// ...and use `num`...
}
与在函数内创建新的 var
相比,这样做会带来非常轻微的性能损失,例如:
function foo(n) {
var num = Math.round(Math.rand() * n);
// ...and use `num`...
}
...但它非常,很可能会被你正在做的其他事情冲掉。
关于javascript - 在函数参数中调用 math.rand,然后缩放并转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10803374/