JS中的Bigint破坏了数组排序?
好像Array.prototype.sort()坏了BigInt
这有效
const big = [1n, 2n, 3n, 4n];
big.sort();
console.log(big);
// expected output: Array [1n, 2n, 3n, 4n]
但这不是:(
const big = [1n, 2n, 3n, 4n];
big.sort((a,b)=>a-b);
console.log(big);
//Error: Cannot convert a BigInt value to a number
还是我做错了什么?
回答
JavaScript 排序方法需要一个函数作为参数,该函数可以比较数组的两个元素并返回正数、负数或零。数字是这里的关键词。
BigInt操作(如加法和减法)返回 BigInt 类型而不是 Number 类型。这就是你得到错误的原因。
所以,像这样的事情应该做的工作
const big = [1n, 2n, 3n, 4n];
big.sort((a ,b) => {
if(a > b) {
return 1;
} else if (a < b){
return -1;
} else {
return 0;
}
});
console.log(big);
有趣的是,我之前链接到的 MDN 文档也建议了如何对 BigInt 数组进行排序,而且很简洁:
在这里复制整个部分以供后代:
const mixed = [4n, 6, -12n, 10, 4, 0, 0n]
// ? [4n, 6, -12n, 10, 4, 0, 0n]
mixed.sort() // default sorting behavior
// ? [ -12n, 0, 0n, 10, 4n, 4, 6 ]
mixed.sort((a, b) => a - b)
// won't work since subtraction will not work with mixed types
// TypeError: can't convert BigInt to number
// sort with an appropriate numeric comparator
mixed.sort((a, b) => (a < b) ? -1 : ((a > b) ? 1 : 0))
// ? [ -12n, 0, 0n, 4n, 4, 6, 10 ]
- You also need to return 0 when `a === b`