//Write a function ‘SplitFunction’ that accepts the string ‘7+12+100’ and splits it into individual values, then summing these values. (Make use of the split() and parseInt() functions). Return the summed result.
you can see the question above, and my code for this question is:
function SplitFunction(str){
let y=str.split('+')
let sum=0
for(i=0;i<y.length;i++){
sum+=parseInt(y[i])
return sum
}
}
console.log(SplitFunction('7+12+100'))
But I keep getting results as 7??? and cant find out why
>Solution :
Just move return sum beyond for loop
function SplitFunction(str){
let y=str.split('+')
let sum=0
for(i=0;i<y.length;i++){
sum+=parseInt(y[i])
}
return sum
}
console.log(SplitFunction('7+12+100'))
Edit
or you can use this clear code below:
var SplitFunction = str => { // taking function called SplitFunction which takes an arguement str
let sum = 0 // set a variable to sum up
str.split(+).forEach(number => { // split taken problem and for each of them:
sum += parseInt(number) // cast to Number and add to sum
})
return sum // finally return result
}