ArraytoString中的参数有什么作用?
我看到了这样的代码。我查了 MDN,但没有提到 toString 有参数。3 在 n.toString(3) 中做什么?
function solution(n) {
n = n.toString(3).split('').reverse().join('')
return parseInt(n, 3)
}
回答
这是Number.prototype.toString(),不是Array.prototype.toString()。它radix作为一个可选参数。
一个介于 2 到 36 之间的整数,指定用于表示数值的基数。
您的代码转换n为 base-3。如果你想将一个数字转换为二进制,你会这样做n.toString(2)
const n = 16,
bases = [2, 3, 4, 10, 16]
console.log(
bases.map(radix => n.toString(radix))
)