Sum of a number for each element in an array [duplicate]

空扰寡人 提交于 2020-01-07 04:08:10

问题


I am working in a redux function where i want for each element in array the sum with n number

This is the code

let neWd = array.map(x => {
  if (x === 'M' || x === 'L'){
    return x;
  }else{
    return x + 5;
  }
}).join(' ')

At the moment return x + 5 is adding the 5 number to any element of the array but not the sum.

How can i achieve it?


回答1:


Assuming you have a string and it is splitted with ' ' and then you get each element as string. You need to cast it to a number, in this example with an unary + for incrementing with 5.

This proposal splits on white space, which can be more than one characters long.

var string = 'M 175 0  L 326.55444566227675 87.50000000000001  L 326.55444566227675 262.5  L 175 350  L 23.445554337723223 262.5  L 23.44555433772325 87.49999999999999 L 175 0',
    array = string.split(/\s+/),
    result = array.map(x => x === 'M' || x === 'L' ? x : +x + 5).join(' ');

console.log(result);


来源:https://stackoverflow.com/questions/41593820/sum-of-a-number-for-each-element-in-an-array

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