javascript - 在函数参数中调用 math.rand,然后缩放并转换为 int

标签 javascript math

我需要在函数的参数内执行指定的操作。我见过一次这样做,但我不记得语法了。

最佳答案

原始答案 请参阅下面的更新答案

...to perform the specified operations within the argumnts of a function...

我不知道“内部”是什么意思。 :-)

但这也许就是您正在寻找的:

function foo(num) {
    return Math.round(Math.rand() * num);
}

更多阅读:

<小时/>

更新答案

在下面回复您的评论:

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/

相关文章:

java - (Noob Coder)基本计算器问题 + 代码建议

math - javascript-标准化数字,使其介于0到1之间

javascript - 圆 Angular 变成矩形?

javascript - MSCRM async javascript SDK.REST.retrieveMultipleRecords 仅返回 50 条记录,一次需要所有记录

javascript - 当这不是我们想要的时,JS 访问对象属性

javascript - 我如何提出评级算法/方程式?

math - 具有无穷大和 nan 的复数乘法/除法

javascript - Jquery Datepicker - 防止在不可用日期范围内选择

javascript - 在没有配置文件的情况下从 JS 运行 karma 测试

math - 单场淘汰赛 - 可能组合的数量