我正在尝试在表示单个二进制值的数组上使用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
最佳答案
问题是您正在更改数组,因为reduce
正在对其进行迭代。这将更改下面的数组,因此该操作与基础值不同步。这是reduce
通常如何遍历数组的(有点宽松)说明:
arr = [1, 2, 3]
^ ^ ^
| | |
iteration 1 -- | |
iteration 2 ----- |
iteration 3 --------
在每次迭代中修改它时,都会发生以下情况:
//start
arr = [1, 2, 3]
//at iteration 1
[2, 3] _
^
|
iteration 1 --
//at iteration 2
[3] _ _
^
|
iteration 2 -----
//at iteration 3
[] _ _
^
|
iteration 3 ------
相反,获得功能的直接方法是使每个项目的幂为2,该幂等于项目的反向索引
//index: 0 1 2 3
arr = [1, 0, 1, 0]
//reverse index: 3 2 1 0
方便地做到这一点,您只需要从数组长度中减去
1
(因为indes是从0开始的,而length = 1仅具有index = 0),然后减去正态索引。这将为您提供两个代表每个值的幂://reverse index: 3 2 1 0
arr = [1, 0, 1, 0]
//power of 2: 8 4 2 1
//multiply and sum: 8 + 0 + 2 + 0 = 10
这是使用
reduce
的代码:const getDecimalValue = function (head) {
let total = head.reduce(
(sum, item, index, array) =>
sum + item * Math.pow(2, (array.length - index - 1)),
// reverse index ^^^^^^^^^^^^^^^^^^^^^^^^
0
)
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)