I need to perform the specified operations within the argumnts of a function. I saw this done once but I disremember the syntax.
1 回答
Original answer see below for updated answer
...to perform the specified operations within the argumnts of a function...
I have no idea what "within" might mean there. :-)
But perhaps this is what you're looking for:
function foo(num) {
return Math.round(Math.rand() * num);
}
More reading:
- MDN's pages on the
Math
object
Updated answer
Re your comment below:
I need the math to happen where it says "num" :).
You can't do that in JavaScript. When declaring a function, all you can put where I have num
above is the names of formal arguments. You can't have expressions there.
You can do this, though:
function foo(num) {
num = Math.round(Math.rand() * num);
// ...and use `num`...
}
There's a very slight performance penalty for doing that rather than creating a new var
within the function, e.g.:
function foo(n) {
var num = Math.round(Math.rand() * n);
// ...and use `num`...
}
...but it's very slight, likely to be washed out by whatever else you're doing.