为什么在NodeListOf上不存在forEach [英] Why forEach does not exist on NodeListOf

查看:164
本文介绍了为什么在NodeListOf上不存在forEach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码:

    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] = [];
        }
    });

但是我遇到了一个错误:

But I got an error:

错误TS2339:类型上不存在属性'forEach'"NodeListOf".

error TS2339: Property 'forEach' does not exist on type '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'方法,为什么"forEach"在"NodeListOf"上不存在?

'NodeListOf' inherit from 'NodeList',and 'NodeList' has 'forEach' method,why 'forEach' does not exist on 'NodeListOf'?

推荐答案

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

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():

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]);
  }
}

这篇关于为什么在NodeListOf上不存在forEach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆