问题
var y= '110001'.split("").reverse();
var sum = 0;
for (var i = 0; i < y.length; i++) {
sum += (y[i] * Math.pow(2, i));
}
console.log(sum);
回答1:
It would be simplest to do
console.log(Array.from('110001').reduce((prev, cur) => prev << 1 | cur));
<<
is the left-bitshift operator, which here essentially multiplies by two.
Array.from
(if available) is preferable to split
. In this case it doesn't matter, but split
will fail with surrogate pair characters such as 🍺, while Array.from
will handle them correctly. This could also be written as [...'110001']
, which ends up being the same thing.
Of course, you could also just say
parseInt('110001', 2)
回答2:
check this snippet
var binary = '110001'.split("").reverse();
var sum = binary.reduce(function(previous, current, index) {
previous = previous + (current * Math.pow(2, index));
return previous;
}, 0);
console.log(sum);
Hope it helps
来源:https://stackoverflow.com/questions/40944740/how-can-i-do-this-using-reduce-function