【问题标题】:Running reduce() on jQuery collection在 jQuery 集合上运行 reduce()
【发布时间】:2019-08-12 08:49:22
【问题描述】:

我正在开发一个应用程序,并且我有一个 DOM 对象集合,我想将它们的组合宽度相加。我想为此使用reduce() 函数。

包含 jQuery 集合的变量名为 menuItems,我的尝试如下所示:

menuItems.toArray().reduce((total, item) => total += item.clientWidth);

但奇怪的是,该函数返回以下输出:

// "http://localhost:3000/97689982"

这相当于字符串中连接在一起的所有宽度不包括第一个元素。

运行menuItems.toArray()[0].clientWidth 之类的东西会正确输出第一项的宽度。

【问题讨论】:

  • menuItems里面的输入数据是什么?你也可以在这里发布吗?

标签: jquery ecmascript-6


【解决方案1】:

需要将客户端宽度从字符串解析为reducing之前的数字。

const totalClientWidth = menuItems.reduce((acc, cur) => acc + Number(cur.clientWidth), 0);

【讨论】:

  • @TylerRoper 修复了它。
猜你喜欢
  • 2011-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-29
  • 2013-11-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多