How can I do this using Reduce function? [closed]

2019-09-23 04:45发布

问题:

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