简体   繁体   中英

What is the easiest method to add individual numbers in a string using javascript

I have some logic within an app that generating strings like the following:

"001"
"021"
"031"

I want to take the single string and split this and add the numbers in a basic efficient manner.

eg for the second string above 021 - desired outcome would be split this to make the sum 0 + 2 + 1 = 3 - how do I split the string by each number using vanilla javascript?

Try this:

 var array = "0123456"; var result = array.split("").reduce((acc, cur) => {return (+acc) + (+cur);},0); console.log(result);

As Bucket said in the comments, this will split the string up into characters, then use array.reduce() to merge all the characters into one value by using an arrow function that converts them to numbers and sums them.

 var str = "021"; var a = str.split(""); // converts the string into an array var result = a.reduce((i, n) => { return Number(i)+ Number(n) },0); console.log(result) //result = 3

 var result = 0; var second = "021"; var arr = second.split(""); for(var i = 0; i < arr.length; i++) result = +arr[i] + result; console.log(result);

This is probably as efficient as you can possible make it, but it does not do any input validation:

var input = "0021031";
var zeroCode = "0".charCodeAt(0);

function sum(input) {
  var result = 0;
  for (var i = 0; i < input.length; ++i) {
    result += input.charCodeAt(i) - zeroCode;
  }
  return result;
}

console.log(sum(input))

 function mathAdd(s) { // take input and split it by '' // use a as the accumulator // use v as the value // add the value to the accumulator and start at 0 // return the value return String(s).split('').reduce((a, v) => a + parseInt(v, 10), 0); } console.log(mathAdd("001")); console.log(mathAdd("021")); console.log(mathAdd("031"));

Adding Numbers in a String :- 
function addNum(nums) {
    let newnums = nums.split(',').map(Number);
    sum = 0;
    for(i=0; i<newnums.length; i++) {
        sum = sum + newnums[i];
    } return sum;
}
console.log(addNum("1, 2, 3, 4, 5, 6, 7"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM