计算类元素的未知/动态数组长度

Counting unknown/dynamic array length of class element

本文关键字:动态 数组 未知 元素 计算      更新时间:2024-03-27

我写了一个简单的代码/用户脚本来通知我webiste上的更改:

function notifier(){
  setTimeout(function () {       
    location.reload(true); 
  },60000)   
}
function notiCounter() {
    console.log("Counting notifications");
    var noti = document.getElementsByClassName("notification");
    for(var i = 0; i < 2; i++) {
        if(noti[i].innerHTML != undefined) {
            console.log(noti[i].innerHTML);
            notifications++;
            console.log("Notifications: " + notifications);
        }
    }
}
function notification(){ 
    setTimeout(function () {
        notiCounter();
        if(notifications > 0){
          document.title = "(" + notifications + ") new notifcations";
          sound.play();
          }
    notifier();
     },50)
}
notification();

问题是,noti[i]的实际最终数是未知/动态的,并且一直在变化,所以如果i < 2被一个更高的数取代,for循环最终会变成一个无限循环——如果我把它选得太低(例如2),如果实际数超过2,数据就会丢失。

你知道那个问题吗?也许这真的很明显,我看不见,因为已经很晚了哈哈。

与其检查i < 2,不如检查i < noti.length。或者,您可以使用for(var i in noti)类型的循环进行迭代。或者更好的是,如果您只想直接获得通知的数量,只需使用noti.length 中的值