【问题标题】:How to get the value of 'index' and put it on a global variable?如何获取'index'的值并将其放在全局变量中?
【发布时间】:2022-06-15 21:45:15
【问题描述】:

如何将 'index' 的值放入全局变量? 只有在 forEach 循环内才会显示索引的值,有没有办法将其取出并放在全局变量中?

stars.forEach((star,index) =>{
    star.addEventListener('click', ()=>{
        stars.forEach((star,idx) =>{
            if(idx < index + 1){
                star.classList.add('active');
            } else {
                star.classList.remove('active');
            }
            console.log(index); // this is working
        });
    });    
});
console.log(index); // this is NOT working

请检查谢谢!

【问题讨论】:

  • 为什么要这样做?每次迭代时索引的值都会发生变化。
  • 全局声明变量,然后为其分配索引
  • 污染全局范围可能是个坏主意。如果你真的需要它(三思而后行),你必须声明一个全局变量然后赋值。

标签: javascript


猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多