为什么Array.prototype.slice.call(nodeList)用于DOM元素? [英] Why do Array.prototype.slice.call(nodeList) for DOM elements?

查看:78
本文介绍了为什么Array.prototype.slice.call(nodeList)用于DOM元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很多JavaScript库(jQuery,Zepto)似乎在querySelectorAll(),getElementsByTag或ClassName结果上调用Array.prototype.slice.call.

通过阅读许多关于StackOverflow的类似问题/答案,我确实了解它可以将NodeList结果转换为真实的Array,以便您可以在NodeLists上不可用的结果上调用Array方法(切片,弹出)-但我不明白的是为什么?通常,您实际上并不需要在DOM节点列表上进行切片/弹出操作,而NodeLists已经具有length属性,因此它们仍然可以遍历.

一些答案​​似乎暗示它是因为NodeList指向活动的DOM对象.但是再次,如果将其转换为数组,则引用仍指向活动的DOM节点-那么有什么区别?

还是我完全想念的其他东西?它是否可以帮助Zepto/jQuery以某种方式缓存DOM元素的多个属性调用?(尽管我真的不知道怎么做,因为它们仍然是实时的DOM引用)

解决方案

通常,您实际上并不需要在DOM节点列表上进行切片/弹出操作

实际上,是的,这就是为什么有必要的原因.

例如, .eq() .first()等如何工作.jQuery对象在数组中包含 NodeList copy ,然后各个方法获取该数组的切片.同样,您不能将 .add()节点添加到 NodeList .

此外,即使随后从DOM中删除了其中的元素,这些数组也需要保持有效.数组中的引用仍然有效,可用于将这些元素重新插入DOM.

如果您所拥有的只是一个实时的 NodeList ,则将这些元素从DOM中删除后,它们会自动从列表中消失,除非您另外引用它们,否则它们将永远丢失./p>

Lots of JavaScript libraries (jQuery, Zepto) seem to be calling Array.prototype.slice.call on querySelectorAll(), getElementsByTag or ClassName results...

From reading many many similar questions/answers on StackOverflow I do understand that its to convert a NodeList result to a real Array so that you can invoke Array methods (slice, pop) on the results which are not available on NodeLists - but what I don't understand is why? You don't usually really need slice/pop on a list of DOM nodes + NodeLists already have a length property so they're traversable anyway.

Some answers seem to imply that its because a NodeList is pointing to live DOM objects. But again if you convert it to an Array, the references are still pointing to live DOM nodes - so whats the difference?

Or is it something else that I'm completely missing? Does it help Zepto/jQuery to somehow cache multiple property calls for DOM elements? (although I don't really see how since those are still live DOM references)

解决方案

You don't usually really need slice/pop on a list of DOM nodes

Actually, you do, and that's exactly why it's necessary.

For example, how else would .eq(), .first(), etc. work. The jQuery object contains a copy of the NodeList in an array, and then the individual methods take slices of that array. Similarly, you can't .add() nodes to a NodeList.

Furthermore, those arrays need to remain valid even if the elements therein are subsequently removed from the DOM. The references in the array are still valid, and can be used to reinsert those elements back into the DOM.

If all you had was a live NodeList the elements would automagically disappear from the list when they're removed from the DOM, and would be lost forever unless you had a separate reference to them.

这篇关于为什么Array.prototype.slice.call(nodeList)用于DOM元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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