Why forEach does not exist on NodeListOf

前端 未结 2 1363
梦如初夏
梦如初夏 2021-01-11 14:01

My code:

    var checkboxes = this.element.querySelectorAll(\"input[type=checkbox]\") as NodeListOf;
    checkboxes.forEach(ele =>         


        
2条回答
  •  青春惊慌失措
    2021-01-11 14:20

    There is no guarantee forEach will exist on this type - it can, but not necessarily (e.g. in PhantomJS and IE), so TypeScript disallows it by default. In order to iterate over it you can use:

    1) Array.from():

    Array.from(checkboxes).forEach((el) => { /* do something */});
    

    2) for-in:

    for (let i in checkboxes) {
      if (checkboxes.hasOwnProperty(i)) {
        console.log(checkboxes[i]);
      }
    }
    

提交回复
热议问题