我使用下面的函数对"columns"一个二维数组,但有些元素包含'-'
,我还没有能够处理它:
我试过Number(num)
或typeof num === 'number'
,但仍然…
const arr = [
['-', 2, 21],
[1, '-', 4, 54],
[5, 2, 2],
[11, 5, 3, 1]
];
const sumArray = (array) => {
const newArray = [];
array.forEach(sub => {
sub.forEach((num, index) => {
if(newArray[index]){
newArray[index] += num;
}else{
newArray[index] = num;
}
});
});
return newArray;
}
console.log(sumArray(arr))
您也可以使用map
和reduce
来实现这一点。
const arr = [
['-', 2, 21],
[1, '-', 4, 54],
[5, 2, 2],
[11, 5, 3, 1],
];
const sums = arr.map((sub) =>
sub.reduce((previous, current) => {
// check here that the value is a number
if (typeof current === 'number') {
return previous + current;
}
return previous;
}, 0)
);
console.log(sums);
// returns [23, 59, 9, 20]
尝试:
const arr = [
['-', 2, 21],
[1, '-', 4, 54],
[5, 2, 2],
[11, 5, 3, 1]
];
const sumArray = (array) => {
const newArray = [];
array.forEach(sub => {
sub.forEach((num, index) => {
if (typeof num == 'number') {
if (newArray[index]) {
newArray[index] += num;
} else {
newArray[index] = num;
}
}
});
});
return newArray;
}
console.log(sumArray(arr))
这里有一个更简洁的解决方案:
const arr = [
['-', 2, 21],
[1, '-', 4, 54],
[5, 2, 2],
[11, 5, 3, 1]
];
const result = arr.map((e, i) => arr.reduce((a, c) => (typeof c[i] == 'number' ? a + c[i] : a), 0))
console.log(result)
使用splice()可以帮助从数组中删除-