javascript - 将变量设置为 2 但 console.log 表示它未定义

标签 javascript jquery html

为了简要概述,我正在创建一个加载栏,它需要从 0 到 100,基于 map 上掉落的图钉总数与可能的位置数量的比较。所以下面我有一些关于我将如何实现这一目标的逻辑。

//pin drop counter
var pDrop = 2;
//secondary drop counter
var dropCounter = pDrop
//result length counter
var rLength;

//pin drops and then runs the check marker count function
function dropPin(){ checkMarkerCount() }

//if a new pin was dropped then we increase the size of the bar 
function checkMarkerCount() {
  if (dropCounter != pDrop) {
    moveBar();
  }

 function moveBar() {
   //selects the loading bar from the DOM
   var barEl = document.getElementById("pro-bar");   
   //states how wide the bar is
   var barW = 1; 
   //dictates how fast it moves
   var barid = setInterval(frame, 10);
   //gets how many pins have dropped
   var counter = pDrop; 

  function frame(counter) {
    //rLength is the length of an array = the total amount of possible pin drops
    if (counter >= rLength) {
      clearInterval(barid);
    } else {
      barW = counter; 
      barEl.style.width = barW + '%'; 
      console.log(barW)
    }
  }
}
}

问题是,即使我说 pDrop 等于 2,它也会记录长度未定义....我做错了什么?

最佳答案

您必须了解变量和参数的概念。

function frame(i_counter) {
    //rLength is the length of an array = the total amount of possible pin drops
    if (i_counter >= rLength) {
      clearInterval(barid);
    } else {
      barW = i_counter; 
      barEl.style.width = barW + '%'; 
      console.log(barW)
    }
  }

当你调用函数框架时,你应该设置params i_counter。 您认为作为参数传递的 counter 与您在上面设置的相同。 代码中的 barW = counter 采用您设置的参数。

我稍微更改了您的代码,因此您没有摆脱 counter 参数。 执行框架时,请执行以下操作:

setInterval(function () {
   frame(2);
}, 10);

关于javascript - 将变量设置为 2 但 console.log 表示它未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48343637/

相关文章:

javascript - 如何让箭头在 Canvas 上移动?

php - 从数据库中检索图像并将其显示在 div 中

javascript - 未捕获的 DOMException : Not able to run codepen code on my html page

javascript - 鼠标 ScrollLeft 不适用于 IE、Firefox、Safari

php - 当用户从 CakePHP 的下拉列表中选择时,在表单中填充 <div>

javascript - 响应式图像上的响应式悬停框

javascript - 一个 html 文件中的多个页面,每一页上没有固定的导航

javascript - 如何替换部分样式背景:url in Blogger Widget

javascript - 在 javascript 中使用 exec() 和正则表达式

jquery - AngularJS:输入值的总和