有人可以解释一下reduce()如何计算数组项的实例并将它们添加到下面代码中的空对象中吗?例如,我们最终得到 { car: 5, Truck: 3 }
。我不太明白 obj[item] 是什么。
const data = ['car', 'car', 'truck', 'truck', 'bike', 'walk', 'car', 'van', 'bike', 'walk', 'car', 'van', 'car', 'truck' ];
const transportation = data.reduce(function(obj, item) {
if (!obj[item]) {
obj[item] = 0;
}
obj[item]++;
return obj;
}, {});
console.log(transportation);//{car: 5, truck: 3, bike: 2, walk: 2, van: 2}
最佳答案
const data = ['car', 'car', 'truck', 'truck', 'bike', 'walk', 'car', 'van', 'bike', 'walk', 'car', 'van', 'car', 'truck' ];
const transportation = data.reduce(function(obj, item) {
console.log(obj, item);
if (!obj[item]) {
obj[item] = 0;
}
obj[item]++;
return obj;
}, {});
console.log(transportation);//{car: 5, truck: 3, bike: 2, walk: 2, van: 2}
如果您可以看到控制台输出,您将看到对象 obj 将充当一个数据结构,其中键作为数组元素,值作为频率,如果属性未定义,它将初始化为 0,在接下来的步骤中,我们只需要增加该值即可。
obj[item] 是对象的属性。当一个唯一的字符串出现时,就会创建这个值,并将其初始化为 0,在接下来的每一步中,我们都会增加这个值
Note in the reduce the first arguments is the object passes on by the previous iteration (initially {}). and the 2nd would traverse through each element
关于javascript - 具体例子理解JavaScript的reduce()方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46543160/