gpt4 book ai didi

javascript - 尝试将 JavaScript 中的 for 循环更改为过滤方法单行

转载 作者:行者123 更新时间:2023-12-01 00:09:44 25 4
gpt4 key购买 nike

我一直在尝试将 for 循环 更改为 filter() 单行代码,但出现此错误:(index):44 Uncaught TypeError :childrenElements.filter 不是函数

工作代码片段:

const parentElement = document.querySelector('.container');

let childrenElements = parentElement.children;

let results = [];

for(i = 0; i < childrenElements.length; i++){
if( childrenElements[i].classList.contains('ui-widget')){
results.push('ui-widget')
}
}

不工作代码片段:

const parentElement = document.querySelector('.container');

let childrenElements = parentElement.children;

let results = [];

results = childrenElements.filter(childrenElement => childrenElement.classList.contains('ui-widget') )

我认为这是因为它无法将 childrenElements 识别为 array,但我不知道如何修复它。

您可以find a demo here

编辑:

接受的答案最终代码片段如下:


const parentElement = document.querySelector('.container');

let childrenElements = parentElement.children;

let results = [];

results = [...childrenElements].map(childrenElement => childrenElement.classList );

console.log(results)

if (results[0].contains('ui-widget')) {
alert('it has class')
}

最佳答案

您可以使用展开运算符将 HTMLCollection 对象转换为数组,以便您的数据可迭代:

results = [...childrenElements].filter(childrenElement => childrenElement.classList );

但是,您似乎正在尝试在元素中查找特定的类。为此,您应该映射元素以创建 classList 数组的数组,然后使用 contains 搜索您要查找的元素。

results = [...childrenElements].map(childrenElement => childrenElement.classList );

if (results[0].contains('ui-widget')) {
alert('it has class');
}

关于javascript - 尝试将 JavaScript 中的 for 循环更改为过滤方法单行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60154384/

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