首页 > 解决方案 > 如何将 jQuery 代码翻译成 Vanilla JS

问题描述

我通常使用 jQuery 作为完成工作的拐杖,然后继续处理下一个问题。然而,随着向 Rails 6 引入 Stimulus,我希望能够更好地编写 vanilla JS。我在重写以下$.map$.each行时遇到了困难:

handleSuccess(data) {
  const items = $.map(data, notification => { return notification.template })
  let unreadCount = 0
  $.each(data, (i, notification) => {
    if (notification.unread) {
      unreadCount += 1
    }
  });
  this.unreadCountTarget.innerHTML = unreadCount
  this.itemsTarget.innerHTML = items
}

我自己的尝试并没有真正奏效。

items.forEach(data, (i, notification) => {
   if (notification.unread) {
     unreadCount += 1
   }
 });

 items.forEach(element, (i, notification) => {
   if (notification.unread) {
     unreadCount += 1
   }
 });

标签: javascriptjqueryruby-on-railsstimulusjs

解决方案


在您的情况下,您可以转换$.map()Array.map(),并将计数器和 转换为$.each()调用Array.reduce()。通常$.each()转换为Array.forEach(),但在这种情况下,您想要获取一个数组,并将其转换为数字,而这种转换通常通过归约来完成。

注意:您自己代码中的问题是由参数的顺序引起的 - $.each(index, item)vs. Array.forEach(item, index)

示例(未测试) - 注释 jQuery 下的香草

handleSuccess(data) {
  // const items = $.map(data, notification => { return notification.template })
  const items = data.map(notification => notification.template)

  // $.each(data, (i, notification) => { if (notification.unread) { unreadCount += 1 }});
  const unreadCount = data.reduce((count, notification, i) => notification.unread ? count + 1 : count, 0)

  this.unreadCountTarget.innerHTML = unreadCount
  this.itemsTarget.innerHTML = items
}

推荐阅读