在JavaScript中,键的对象的Sum数组为2个以上的项返回NaN
下面是我的数组-在JavaScript中,键的对象的Sum数组为2个以上的项返回NaN,javascript,ecmascript-6,reduce,Javascript,Ecmascript 6,Reduce,下面是我的数组- const products = [{ id: "1", quantity: 3 }, { id: "2", quantity: 3 }] console.log(products.reduce((acc, product) => acc.quantity + product.quantity)) // 6 -> Correct 但若数组包含2个以上的项,它会抛出NaN,请告诉我我在这里做错了什么 const products = [{ id
const products = [{
id: "1",
quantity: 3
}, {
id: "2",
quantity: 3
}]
console.log(products.reduce((acc, product) => acc.quantity + product.quantity)) // 6 -> Correct
但若数组包含2个以上的项,它会抛出NaN,请告诉我我在这里做错了什么
const products = [{
id: "1",
quantity: 3
}, {
id: "2",
quantity: 3
}, {
id: "3",
quantity: 4
}]
console.log(products.reduce((acc, product) => acc.quantity + product.quantity)) // NaN -> InCorrect
默认情况下,累加器的初始值是数组中的第一个元素。如果第一个元素是一个对象,那么向该对象添加任何内容都将导致NaN 只需提供另一个参数reduce,为累加器提供初始值,并确保累加器记录总和: 常数乘积=[{ id:1, 数量:3 }, { id:2, 数量:3 }, { id:3, 数量:4 }]; const total=products.reduceacc,product=>acc+product.quantity,0;
console.logtotal 默认情况下,累加器的初始值是数组中的第一个元素。如果第一个元素是一个对象,那么向该对象添加任何内容都将导致NaN 只需提供另一个参数reduce,为累加器提供初始值,并确保累加器记录总和: 常数乘积=[{ id:1, 数量:3 }, { id:2, 数量:3 }, { id:3, 数量:4 }]; const total=products.reduceacc,product=>acc+product.quantity,0; console.logtotal 原因第二次acc为6,acc.数量未定义。要解决此问题,请将acc.QUOTE替换为acc,并使用0作为启动累加器因为acc第二次为6,acc.QUOTE未定义。要解决此问题,请将acc.quantity替换为acc,并使用0作为起始累加器此方法对累加器和数组中的每个元素从左到右应用函数,以将其减少为单个值 在您的acc变量中,它包含值,而不是您直接添加的对象和这样的新数量 演示 常数乘积=[{ id:1, 数量:3 }, { id:2, 数量:3 }, { id:3, 数量:4 }]; 让result=products.reduceacc,{quantity}=>acc+quantity,0; console.logresult .as console wrapper{max height:100%!important;top:0;}该方法对累加器和数组中的每个元素从左到右应用函数,以将其减少为单个值 在您的acc变量中,它包含值,而不是您直接添加的对象和这样的新数量 演示 常数乘积=[{ id:1, 数量:3 }, { id:2, 数量:3 }, { id:3, 数量:4 }]; 让result=products.reduceacc,{quantity}=>acc+quantity,0; console.logresult .作为控制台包装{最大高度:100%!重要;顶部:0;} 这个很好用 这个很好用
<script>
const products = [{id: "1", quantity: 3},{id: "2",
quantity: 3},{id: "3", quantity: 4}];
total = Object.values(products).reduce((t, n) => t
+ n.quantity, 0);
console.log(total);
</script>