为了简要概述,我正在创建一个加载栏,它需要从 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/