javascript - 如何将 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
}
});
解决方案
在您的情况下,您可以转换$.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
}
推荐阅读
- c# - 配置 HttpClient 以使用服务填充身份验证标头?
- java - Google Play 订阅:“帐户保留”和“宽限期”之间的干扰
- c++ - 模板化模板参数 U
不识别 const 限定符 - dynamics-crm - 在 Microsoft Dynamics 365 中批量更新实体消息
- php - PHP、未定义索引、isset 和单选按钮
- python - 如何在 tensorflow 的 Conv 层中制作一个/一些过滤器?
- angular - 返回 Observable 时,Angular 路由守卫无法按预期工作
- python - MemoryError:无法为 DIPY 图像配准中形状 (344、344、127) 和数据类型 float64 的数组分配 115.MiB
- c# - 缺少程序集参考 - 确保 VS 为我的 nuget 包创建一个 .config 文件
- android - 为什么从 jobject 或 jclass 或简单的 QString 创建 QAndroidJniObject 失败而没有错误?