当我使用 reduce 方法编写以下代码时,值不精确:
return bytes.reduce((accumulator, currentValue, index) => {
return accumulator + (currentValue * Math.pow(256,(bytes.length - 2) - index));
}
)
例如。输出数字5.99609375, 10.99609375, 7.99609375, 14.99609375
但是当我编写以下代码时,结果是精确的:
let result = 0.0;
for (let i = 0; i < bytes.length - 1; ++i) {
result = result + (bytes[i] * Math.pow(256, (bytes.length - 2) - i));
}
return result
例如。输出数字5, 10, 7, 14
输入字节数组是:
Uint8Array(4) [0, 0, 5, 255]
Uint8Array(4) [0, 0, 10, 255]
Uint8Array(4) [0, 0, 7, 255]
Uint8Array(4) [0, 0, 14, 255]
这是为什么?有没有办法使 reduce 方法精确工作?
const res = document.getElementById('result');
const res2 = document.getElementById('result2');
const arr = a = [
[0, 0, 5, 255],
[0, 0, 10, 255],
[0, 0, 7, 255],
[0, 0, 14, 255]
];
const fn = (bytes) => {
let result = 0.0;
for (let i = 0; i < bytes.length - 1; ++i) {
result = result + (bytes[i] * Math.pow(256, (bytes.length - 2) - i));
}
return result
}
fn2 = (bytes) => {
return bytes.reduce((accumulator, currentValue, index) => {
return accumulator + (currentValue * Math.pow(256, (bytes.length - 2) - index));
})
}
res.innerText += `${arr.map(fn)}`;
res2.innerText += `${arr.map(fn2)}`;
<div id="result"></div>
<div id="result2"></div>