计算数组中的真实出现次数并将它们绑定到 angular 中的变量
Counting true occurences in array and binding them to a variable in angular
我有一组带有复选框的输入字段,用户可以在其中选择一个选项。然后将其保存在本地存储中,如果选中则为 true,否则为 false。键“passengers”下的 localStorage 如下所示:
0: {name: "", child: false, luggage: true}
1: {name: "", child: true, luggage: false}
2: {name: "", child: false, luggage: true}
3: {name: "", child: true, luggage: false}
我想计算 true 的出现次数并将其作为数字存储在变量中
public luggageCounter: number;
我正在尝试使用
this.luggageCounter = countTrue([this.passengers[i].luggage]], true)
console.log(this.luggageCounter)
和const countTrue = (arr, val) => arr.reduce((a, v) => (v === val ? a +1 : a), 0)
但这两种解决方案都不起作用。我也在考虑通过在下面添加 [ngClass] 代码并将其与 component.ts 中的方法绑定但也没有成功。 HTML 中的值变得更容易并切换值。
<div>Extra luggage: {{ passengers[i].luggage ? 'Yes' : 'No' }}<div>
有什么想法可以让这个简单的任务发挥作用吗?我没主意了:)
请尝试以下解决方案
const data = [
{ name: "", child: false, luggage: true },
{ name: "", child: true, luggage: false },
{ name: "", child: false, luggage: true },
{ name: "", child: true, luggage: false },
];
const total = data.reduce((previousValue, currentValue) => {
if (currentValue.luggage) {
previousValue += 1;
}
return previousValue;
}, 0);
console.log(total);
见
我有一组带有复选框的输入字段,用户可以在其中选择一个选项。然后将其保存在本地存储中,如果选中则为 true,否则为 false。键“passengers”下的 localStorage 如下所示:
0: {name: "", child: false, luggage: true}
1: {name: "", child: true, luggage: false}
2: {name: "", child: false, luggage: true}
3: {name: "", child: true, luggage: false}
我想计算 true 的出现次数并将其作为数字存储在变量中
public luggageCounter: number;
我正在尝试使用
this.luggageCounter = countTrue([this.passengers[i].luggage]], true)
console.log(this.luggageCounter)
和const countTrue = (arr, val) => arr.reduce((a, v) => (v === val ? a +1 : a), 0)
但这两种解决方案都不起作用。我也在考虑通过在下面添加 [ngClass] 代码并将其与 component.ts 中的方法绑定但也没有成功。 HTML 中的值变得更容易并切换值。
<div>Extra luggage: {{ passengers[i].luggage ? 'Yes' : 'No' }}<div>
有什么想法可以让这个简单的任务发挥作用吗?我没主意了:)
请尝试以下解决方案
const data = [
{ name: "", child: false, luggage: true },
{ name: "", child: true, luggage: false },
{ name: "", child: false, luggage: true },
{ name: "", child: true, luggage: false },
];
const total = data.reduce((previousValue, currentValue) => {
if (currentValue.luggage) {
previousValue += 1;
}
return previousValue;
}, 0);
console.log(total);
见