减少对象中的数组
Reduce arrays in object
假设我在对象数组中分配了值。我想使用 reduce() 将它们相加。工作流程将像这样工作: x-data=" {package_type: [], online_implant_meeting: [], total() { return "do the math here" }} 然后在里面x-text="总计()"
我正在使用 alpine.js 来绑定东西。如何在函数内部进行计算?
<div class="addingPrices" x-data="{package_type: [20], online_implant_meeting: [250], total(package_type, online_implant_meeting){
return package_type + online_implant_meeting;
}} >
</div>
这是通过 spread operator (to merge the 2 arrays) and then sum them up with reduce:
实现的一种方法
<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine.js"></script>
<div class="addingPrices" x-data="{
package_type: [89],
online_implant_meeting: ['150'],
total(package_type, online_implant_meeting) {
return [...package_type, ...online_implant_meeting].map(Number).reduce((acc, curr) => acc + curr, 0)
}
}">
<span x-text.number="total(online_implant_meeting, package_type )"></span>
</div>
假设我在对象数组中分配了值。我想使用 reduce() 将它们相加。工作流程将像这样工作: x-data=" {package_type: [], online_implant_meeting: [], total() { return "do the math here" }} 然后在里面x-text="总计()"
我正在使用 alpine.js 来绑定东西。如何在函数内部进行计算?
<div class="addingPrices" x-data="{package_type: [20], online_implant_meeting: [250], total(package_type, online_implant_meeting){
return package_type + online_implant_meeting;
}} >
</div>
这是通过 spread operator (to merge the 2 arrays) and then sum them up with reduce:
实现的一种方法<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine.js"></script>
<div class="addingPrices" x-data="{
package_type: [89],
online_implant_meeting: ['150'],
total(package_type, online_implant_meeting) {
return [...package_type, ...online_implant_meeting].map(Number).reduce((acc, curr) => acc + curr, 0)
}
}">
<span x-text.number="total(online_implant_meeting, package_type )"></span>
</div>