对不起,这是基本的东西,但我不懂java脚本数组
我有一个简单的数组,索引数相同,数组数n
,如果索引没有值,它将是null
Array [
0: Array [ null, 10222, 10222, null,9999 ]
1: Array [ 1870963, 1845801, 1830263, null, null ]
2: Array [ 1870963, 1845801, 1830263, null, null ]
n: Array [ n, n, n, n, n ]
];
所以我需要在单个数组中使用和如下所示。
Array [3741926,3701824,3670748,0,9999];
只需要将总和变成单个数组。
答案 0 :(得分:3)
使用Array#map迭代数组,并使用Array#reduce对每列求和:
var arr = [
[null, 10222, 10222, null, 9999],
[1870963, 1845801, 1830263, null, null],
[1870963, 1845801, 1830263, null, null],
];
var result = arr[0].map(function(a, i) {
return arr.reduce(function(s, n) {
return s + n[i];
}, 0);
});
console.log(result);
答案 1 :(得分:2)
你可以这样使用reduce
:
const a = [
[ null, 10222, 10222, null,9999 ],
[ 1870963, 1845801, 1830263, null, null ],
[ 1870963, 1845801, 1830263, null, null ]
];
console.log(a.reduce((acc, cur) => acc.map((x, i) => x + cur[i])))
答案 2 :(得分:1)
您可以使用array.prototype.map
和array.prototype.reduce
:
var arr = [
[ null, 10222, 10222, null,9999 ],
[ 1870963, 1845801, 1830263, null, null ],
[ 1870963, 1845801, 1830263, null, null ]
];
var result = arr[0].map((_, i) => arr.reduce((m, e) => m + e[i], 0));
console.log(result);
答案 3 :(得分:0)
您可以将@Component({
selector: 'jhi-company-user-dialog',
templateUrl: './company-user-dialog.component.html'
})
export class CompanyUserDialogComponent implements OnInit {
constructor(private companyService: CompanyService) {
}
save() {
console.log(this.user)
this.doNotMatch = null;
this.isSaving = true;
if (this.user.password !== this.confirmPassword) {
this.doNotMatch = 'ERROR';
}else if (this.user.id !== null) {
this.userService.update(this.user).subscribe((response) =>
this.onSaveSuccess1(response), () => this.onSaveError());
} else {
this.userService.create(this.user).subscribe((response) =>{
console.log(response);
this.onSaveSuccess1(response), () => this.onSaveError()
});
}
}
与array#reduce
一起使用。
array#foreach