为什么.includes()不能与.classList一起使用?
element.classList
返回一个类数组,我的理解.includes()
用于数组,所以我不明白为什么这不会工作,我知道我可以使用.contains()与classList,但我很好奇为什么.includes()不起作用。
element.classList
returns an array of classes, its my understanding .includes()
is used with arrays, so I don't understand why this wont work, I know I can use .contains() with classList but I'm curious as to why .includes() doesn't work.
两者都是数组,如果我输入这个例如它就不会工作
both are arrays, if I typed this for example it wont work
var li=document.createElement('li');
li.classList.add('main-nav');
li.classList.includes('main-nav');
但这将
var ary=['a','b','c'];
ary.includes('a');
Element.classList
是 DOMTokenList 对象,虽然它在控制台中打印出类似数组的对象。但是如果你试试Firefox,它会返回 DOMTokenList [main-nav]
Element.classList
is a DOMTokenList object, though it prints an array-like in console. But if you try on Firefox, it'd return DOMTokenList["main-nav"]
并且, includes 是方法 数组而不是 DOMTokenList 。
这就是为什么在你的情况下遇到 li.classList.includes不是函数
的原因。
Which is why it's expected to encounter li.classList.includes is not a function
in your case.
您可以使用 ES2015传播运算符将其转换为数组。
You can use ES2015 spread operator to cast it to be an array.
[...li.classList].includes('main-nav')
或者,您可以使用 DOMTokenList.contains 方法。
Or alternatively, you can use DOMTokenList.contains method.
li.classList.contains('main-nav')
为什么声明为包含
而不是有
或包含
? (感谢@akinuri)
Why is it declared as includes
instead of has
or contains
? (thanks to @akinuri)
从提案
网络上有像 DOMStringList 和 DOMTokenList
类似于数组,并且具有名为包含,其中
的语义与我们的包括。不幸的是,与那些
的网格划分不是网络兼容的。
The web has classes like DOMStringList and DOMTokenList which are array-like, and have methods named contains with the same semantics as our includes. Unfortunately, meshing with those is not web-compatible.