猿问

Javascript 中 BigInt 类型的 Math.max 和 Math.min 的替代方案

在 Javascript 中:Math.max 和 Math.min 不适用于 BigInt 类型。


例如:


> Math.max(1n, 2n)

Thrown:

TypeError: Cannot convert a BigInt value to a number

    at Math.max (<anonymous>)

>

是否有在 BigInts 上执行这些操作的内置函数?


摇曳的蔷薇
浏览 244回答 2
2回答

繁花不似锦

怎么样const bigIntMax = (...args) => args.reduce((m, e) => e > m ? e : m);const bigIntMin = (...args) => args.reduce((m, e) => e < m ? e : m);如果你想要两个const bigIntMinAndMax = (...args) => {&nbsp; return args.reduce(([min,max], e) => {&nbsp; &nbsp; &nbsp;return [&nbsp; &nbsp; &nbsp; &nbsp;e < min ? e : min,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;e > max ? e : max,&nbsp; &nbsp; &nbsp;];&nbsp; }, [args[0], args[0]]);};const [min, max] = bigIntMinAndMax(&nbsp; &nbsp;BigInt(40),&nbsp; &nbsp;BigInt(50),&nbsp; &nbsp;BigInt(30),&nbsp; &nbsp;BigInt(10),&nbsp; &nbsp;BigInt(20),);

陪伴而非守候

经过一番谷歌搜索后,答案似乎是否定的,Javascript 对此没有内置函数。这是与内置签名匹配的 bigint 的 min 和 max 的实现,除了它会为空列表引发错误(而不是返回 +/-Infinity,因为 BigInt 不能表示无穷大):function bigint_min(...args){&nbsp; &nbsp; if (args.length < 1){ throw 'Min of empty list'; }&nbsp; &nbsp; m = args[0];&nbsp; &nbsp; args.forEach(a=>{if (a < m) {m = a}});&nbsp; &nbsp; return m;}function bigint_max(...args){&nbsp; &nbsp; if (args.length < 1){ throw 'Max of empty list'; }&nbsp; &nbsp; m = args[0];&nbsp; &nbsp; args.forEach(a=>{if (a > m) {m = a}});&nbsp; &nbsp; return m;}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答