You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将这段使用箭头函数的JavaScript代码转换为普通函数?

转换为普通函数版本的代码

下面是把你提供的箭头函数替换为普通函数后的代码:

const arrows = document.querySelectorAll(".arrow");
const movieLists = document.querySelectorAll(".movie-list");

arrows.forEach(function(arrow, i) {
   const itemNumber = movieLists[i].querySelectorAll("img").length;
   let clickCounter = 0;
   arrow.addEventListener("click", function() {
      const ratio = Math.floor(window.innerWidth / 270);
      clickCounter++;
      if (itemNumber - (4 + clickCounter) + (4 - ratio) >= 0) {
        movieLists[i].style.transform = `translateX(${movieLists[i].computedStyleMap().get("transform")[0].x.value - 300}px)`;
      } else {
        movieLists[i].style.transform = "translateX(0)";
        clickCounter = 0;
      }
   });
});

替换说明:

  • 将arrows.forEach((arrow, i) => {})中的箭头函数替换为function(arrow, i) {}
  • 将addEventListener的箭头回调() => {}替换为function() {}

由于原代码中没有依赖箭头函数的this绑定特性(这里使用的是外部作用域的i、itemNumber等变量),所以直接替换为普通函数即可正常运行。

内容的提问来源于stack exchange,提问作者Hanishkaran Muneswaran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 12:39:50