gpt4 book ai didi

javascript - 为什么 NodeListOf 上不存在 forEach

转载 作者:可可西里 更新时间:2023-11-01 02:49:35 24 4
gpt4 key购买 nike

我的代码:

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

但是我得到一个错误:

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' 方法,为什么'NodeListOf'上不存在'forEach'?

最佳答案

无法保证 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]);
}
}

关于javascript - 为什么 NodeListOf 上不存在 forEach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47492595/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com