数组中每个元素的数字之和 [英] Sum of a number for each element in an array

查看:106
本文介绍了数组中每个元素的数字之和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个redux函数中工作,我想为数组中的每个元素添加n个数字

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

这是代码

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

此刻 return x + 5 正在添加 5 数字到数组的任何元素,但不是总和。

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

我如何实现?

推荐答案

假设你有一个字符串,它被分割成'',然后你将每个元素作为字符串。您需要将其转换为一个数字,在本示例中,与 5 递增的一元 +

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);

这篇关于数组中每个元素的数字之和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆