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

倖福魔咒の 提交于 2019-12-25 18:51:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!