【问题标题】:Why forEach does not exist on NodeListOf为什么 NodeListOf 上不存在 forEach
【发布时间】:2019-01-29 10:14:34
【问题描述】:

我的代码:

    var checkboxes = this.element.querySelectorAll("input[type=checkbox]") as NodeListOf<HTMLInputElement>;
    checkboxes.forEach(ele => {
        var key = ele.name;
        if (data.hasOwnProperty(key)) {
            if (!this.isArray(data[key])) {
                var temp = data[key];
                data[key] = [temp];
            }
        } else {
            data[key] = [];
        }
    });

但我得到了一个错误:

错误 TS2339:类型上不存在属性“forEach” 'NodeListOf'。

interface NodeListOf<TNode extends Node> extends NodeList {
    length: number;
    item(index: number): TNode;
    [index: number]: TNode;
}

interface NodeList {
    /**
     * Returns an array of key, value pairs for every entry in the list
     */
    entries(): IterableIterator<[number, Node]>;
    /**
     * Performs the specified action for each node in an list.
     * @param callbackfn  A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the list.
     * @param thisArg  An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
     */
    forEach(callbackfn: (value: Node, index: number, listObj: NodeList) => void, thisArg?: any): void;
    /**
     * Returns an list of keys in the list
     */
    keys(): IterableIterator<number>;

    /**
     * Returns an list of values in the list
     */
    values(): IterableIterator<Node>;


    [Symbol.iterator](): IterableIterator<Node>;
}

“NodeListOf”继承自“NodeList”,“NodeList”有“forEach” 方法,为什么'NodeListOf'上不存在'forEach'?

【问题讨论】:

  • 因为它只存在于Array。不知道你在这里寻找什么样的答案。如果您想使用forEach,请使用Array.from()
  • @jhpratt NodeList 有一个forEach 方法:NodeList.prototype.forEach

标签: javascript typescript


【解决方案1】:

不保证 forEach 会在这种类型上存在 - 它可以,但不一定(例如在 PhantomJS 和 IE 中),因此默认情况下 TypeScript 不允许它。为了对其进行迭代,您可以使用:

1) Array.from():

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

2) 换入:

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

【讨论】:

  • 您确定答案 2 有效吗?我收到错误消息:“类型 'NodeListOf' 不是数组类型或字符串类型。”。
  • 你是对的,只有 for-in 循环才能使用 TypeScript,谢谢。
【解决方案2】:

老实说,您可以将 NodeListOf 转换为数组,这样打字稿就不会抱怨 nodelist.forEach,但这只是通过添加不必要的代码来解决问题。您可以通过将 dom.iterable 库添加到 tsconfig.json 来告诉 typescript 理解本机 nodelist.forEach 语法。这是我的 tsconfig.json 文件之一的示例。

{
  "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"
  ]
}

并非所有浏览器都支持 nodelist.forEach 所以我肯定会填充它https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach

【讨论】:

  • 我还必须将"downlevelIteration: true 添加到compilerOptions,如here 所述。如果您想减小发出的 JS 文件大小,可以添加 tslib 以及标志 importHelpersnoEmitHelpers
猜你喜欢
  • 1970-01-01
  • 2015-09-29
  • 2010-11-17
  • 1970-01-01
  • 2011-01-25
  • 2022-01-25
  • 1970-01-01
  • 2019-08-21
相关资源
最近更新 更多