[英]What is the easiest method to add individual numbers in a string using javascript
我在應用程序中有一些邏輯可以生成如下字符串:
"001"
"021"
"031"
我想取單個字符串並將其拆分並以基本有效的方式添加數字。
例如,對於021
以上的第二個字符串 - 期望的結果將被拆分為總和0 + 2 + 1 = 3
- 如何使用 vanilla javascript 按每個數字拆分字符串?
嘗試這個:
var array = "0123456"; var result = array.split("").reduce((acc, cur) => {return (+acc) + (+cur);},0); console.log(result);
正如 Bucket 在評論中所說,這會將字符串拆分為字符,然后使用array.reduce()
將所有字符合並為一個值,方法是使用箭頭函數將它們轉換為數字並將它們相加。
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);
這可能盡可能高效,但它不進行任何輸入驗證:
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"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.