Could anyone help me please.
I have created a function and within it I have an array containing string representations of integers.
var a = ['11', '22', '33' ,'44'];
What I am trying to do is to get a sum of individual digits in each element of the array. For example, the element containing '11'
would give me 2
(1 + 1), '22'
would give me 4
(2 + 2), and so on... So I should get [2,4,6,8]
as the final output. How can I do this.
Thank you,
答案 0 :(得分:3)
答案 1 :(得分:2)
map
,拆分每个元素,将其转换为数字然后添加它们,然后返回最终数组。
function thing(arr) {
return arr.map(function (el) {
return el.split('').map(Number).reduce(function (p, c) {
return p + c;
});
});
}
thing(arr) // [ 2, 4, 6, 8 ]
或者更糟糕的ES6:
const add = (a, b) => a + b;
function sumElements(arr) {
return arr.map(el => [...el].map(Number).reduce(add));
}
答案 2 :(得分:1)
使用数学的另一种方法:
var a = ['11', '22', '33' ,'44'];
var res = a.map(Number).map(function(digit) {
var result = 0;
while(digit) {
result += digit % 10;
digit = Math.floor(digit/10);
}
return result;
});
document.write(res);

答案 3 :(得分:1)
一张<div>
ES6
答案 4 :(得分:1)
这适用于所有浏览器:
JSON.Parse()
答案 5 :(得分:0)
I'm not sure this is what you are asking, but I'll give it a go.
var a = [11,22,33,44];
var b = [];
for(i in a){
b.push(a[i]*2);
}
//b == [22,44,66,88]
Your array is strings so you might want to wrap a[i]
in the Number()
function.