如何将jQuery代码转换为Vanilla JS

我通常使用jQuery作为拐杖来完成工作,然后继续处理下一个问题。但是,随着Rails 6的Stimulus的引入,我希望更好地编写香草JS。我在重新编写下面的$.eachhandleSuccess(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,notification) => {
   if (notification.unread) {
     unreadCount += 1
   }
 });

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

我自己的尝试未达到实际效果。

{{1}}
dongyafei123 回答:如何将jQuery代码转换为Vanilla JS

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

注意:您自己的代码中的问题是由参数的顺序-$.each(index,item)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
}
,

JavaScript有其自身的本机地图功能(很长一段时间没有,因此是jQuery shim),它与jQuery非常相似。实际上,Array.prototype.map()和Array.prototype.forEach()都非常相似,具有相似的接口,只需从数组名称开始调用即可。因此,它是$.map(data,notification => { return notification.template })或类似的词,而不是jQuery data.map(notification => notification.template)。而且本机map()和forEach()之间的唯一区别是,forEach()将函数应用于数组中的每个项目,而map()则向前走了一步,如果正确调用,则会返回一个新的结果值数组。>

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

,

尝试一下:

handleSuccess(data){
const items = data.map(notification => notification.template)

let unreadCount = items.reduce(( total,curr) => curr.unread ? total +=1 : total)

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

代码的最后两行不变。

本文链接:https://www.f2er.com/3157000.html

大家都在问