【问题标题】:Reduce arrays in object减少对象中的数组
【发布时间】:2020-12-30 21:10:38
【问题描述】:

假设我在对象的数组中分配了值。我想用 reduce() 把它们加起来。工作流程将像这样工作: x-data=" {package_type: [], online_implant_meeting: [], total() { return "do the math here" }} 然后在 x-text="total()"

我正在使用 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>

【问题讨论】:

  • 我以前没有使用过 alpine.js。你能以这种方式访问​​函数内部的package_typeonline_implant_meeting(假设你要访问console.log 他们)?
  • 我可以在控制台 total(item, item) 时访问它们。问题是我得到了彼此附加的值。 20250

标签: javascript alpine.js


【解决方案1】:

这是通过spread operator(合并2个数组)然后将它们与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>

【讨论】:

  • ```
    ``` &lt;span x-text.number="total([online_implant_meeting],[package_type] )"&gt;&lt;/span&gt; .现在我得到的值为 015089.00 假设值为 89, 150
  • 在你的 &lt;span&gt; 中,只需执行 x-text.number="total(online_implant_meeting, package_type )"(不带方括号) - 这些变量已经引用了数组值,我在示例中添加了大括号,因为我正在通过数字文字对其进行测试跨度>
  • 返回相同的值 015089.00
  • 只需添加.map(Number) 即可修复它。像这样:return [...online_implant_meeting, ...package_type].map(Number).reduce((acc, curr)=&gt; acc + curr, 0);
  • 我欠你的。非常感谢。我是声明式 javascript 的新手。
猜你喜欢
相关资源
最近更新 更多
热门标签