Why forEach does not exist on NodeListOf

前端 未结 2 1340
梦如初夏
梦如初夏 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:18

    Honestly you could convert a NodeListOf to an array so that typescript will not complain about nodelist.forEach, but this is only solving the problem by adding unnecessary code. You can tell typescript to understand the native nodelist.forEach syntax by adding the dom.iterable library to your tsconfig.json. Here is an example of one of my tsconfig.json files.

    {
      "compilerOptions": {
      "outDir": "./public/js/",
      "noImplicitAny": true,
      "module": "es6",
      "target": "es5",
      "allowJs": true,
      "moduleResolution": "node",
      "rootDir": "src",
      "lib": [
        "es6",
        "dom",
        "dom.iterable"
      ],
      "typeRoots": [
        "node_modules/@types"
      ],
      "removeComments": false
      },
      "include": [
        "src/**/*.ts"
      ],
      "exclude": [
        "node_modules",
        "public",
        "**/*.spec.ts"
      ]
    }
    

    Not all browsers support nodelist.forEach so I would definitely polyfill it https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach

    0 讨论(0)
  • 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]);
      }
    }
    
    0 讨论(0)
提交回复
热议问题