【发布时间】:2020-04-28 12:18:49
【问题描述】:
我正在尝试在表示单个二进制值的数组上使用 array.reduce。例如二进制的 [1,0,1] 将转换为十进制的 5。
我已经能够使用 while 循环成功地在二进制和十进制之间进行转换,但我想升级我的代码以使用 reduce 方法。
到目前为止,我已经实现了精确到数组中的 6 个元素。我不知道为什么,但在 6 位数之后,转换失败。
此外,我正在使用公式进行转换。例如:要将 111001 转换为十进制,您必须执行 (1*2^5) + (1*2^4) (1*2^3) + (0*2^2) + (0*2^ 1) + (1*2^0)。
const getDecimalValue = function (head) {
let total = head.reduce(
(sum) =>
sum + (head.shift() * Math.pow(2, head.length))
)
return total
}
console.log(getDecimalValue([1, 0, 1]) == 5)
console.log(getDecimalValue([1, 1, 1, 0, 0, 1]) == 57)
console.log(getDecimalValue([1, 1, 1, 0, 0, 1, 1]) == 115)
console.log(getDecimalValue([0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0]) == 7392)
console.log(getDecimalValue([1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0]) == 18880)
这是我使用 while 循环的代码
let sum = 0
while ((i = head.shift()) !== undefined) {
sum += (i * Math.pow(2, head.length))
console.log(i * Math.pow(2, head.length))
}
return sum
【问题讨论】:
-
您在迭代数组时正在对其进行变异。只是......不要那样做,因为在你转移出指数后,你会让整个操作出错。
-
我希望这里提出的所有问题都在范围内如此清晰,并带有自己的测试。为此 +1!
标签: javascript arrays binary reduce