You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何调用不可修改的内置函数时传入相同随机参数?

Great question! You absolutely can do this in one line without declaring a separate variable, though the approach depends on whether you're working with JavaScript or Java (since Math.random() exists in both):

For JavaScript

The cleanest, non-global-polluting way is to use an immediately-invoked arrow function that generates a single random value and returns it twice in an array, then spread that array into your foo call:

foo(...(() => { const r = Math.random(); return [r, r]; })());

Here, Math.random() runs exactly once, both arguments get the same value, and no extra variables stick around after the call.

If you don't mind a temporary global variable (not recommended for production code due to naming collision risks), you can use a comma expression for even shorter syntax:

foo((r = Math.random()), r);

For Java

Java's syntax is stricter, so a truly elegant one-liner without any variable declaration is tricky. The problem is Java doesn't let you reuse an anonymous object or lambda result multiple times in the same expression without storing it in a variable.

If you're okay with declaring a variable on the same line (still one line of code overall), this is the most readable approach:

double rand; foo((int)(rand = Math.random()), (int)rand);

This calls Math.random() once, stores it in rand, and passes it twice to foo—clean and easy to understand.

If you absolutely refuse to declare any variables, you could use a messy hack with an anonymous inner class, but it's unreadable and not worth it in most cases (plus, you'd accidentally call Math.random() twice if you're not careful). Your original variable-based approach is far better for maintainability here.

内容的提问来源于stack exchange,提问作者Nick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 16:02:59