首页 > 解决方案 > 存储迭代计数,然后在 javascript 中的 for 循环之外访问它

问题描述

我想我误解了提升的工作原理,但我对为什么返回的 i++ 没有被提升到 var i 的初始声明感到困惑。对于上下文,我正在尝试创建利用 scrollIntoView() 在 div 之间循环的上一个/下一个按钮。

我让它按预期用于下一个按钮(单击并循环到下一个 div),但问题是我似乎无法将 i 的当前值存储在 for 循环之外,以便我可以在另一个内部使用 stepsTotal[i]函数(用于处理单击时的上一个按钮)。

这是我为下一个按钮工作的代码(不包括上一个按钮功能)。当单击下一个按钮时,我试图让 console.log(i) 打印 0、1、2、3 等。)

const stepsTotal = document.getElementsByClassName("question-steps");

const currentStep = (function() {
  var i;
  console.log(i); // How do I have this print the current value of i instead of undefined? (i.e. match the results of the second console.log)

  for (i=0; i<stepsTotal.length; i++) {
    document.getElementById("next-button").addEventListener("click", scrollToCurrentStep);

    function scrollToCurrentStep() {
      stepsTotal[i].scrollIntoView(true);
      i++;
      console.log(i); // I want the first console.log to match this one
      return
    }
    return
  }
}());

标签: javascript

解决方案


推荐阅读