问题
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