4

我在 js 插件中发现了以下锥体

var container = document.getElementById( 'vs-container' ),
wrapper = container.querySelector( 'div.vs-wrapper' ),
sections = Array.prototype.slice.call( wrapper.querySelectorAll( 'section' ) ),
links = Array.prototype.slice.call( container.querySelectorAll( 'header.vs-header > ul.vs-nav > li' ) );

我无法理解上面代码中的作用Array.prototype.slice.call()和作用。wrapper.querySelectorAll( 'section' )我以前没有见过他们,所以我想知道他们实际上做了什么。

4

2 回答 2

4

querySelectorAll是 DOM 元素上的一种方法,它接受 CSS 选择器并返回NodeList匹配元素的静态。

Array.prototype.slice.call是将它NodeList(它像一个数组,但没有 from 的方法Array.prototype)变成一个真正的数组的一种方法。

在浏览器控制台中的此页面上试一试!

> var headers = document.querySelectorAll('h1, h2, h3, h4, h5, h6');
undefined
> headers.map(function(el) { return el.textContent; })
TypeError: Object #<NodeList> has no method 'map'
> headers = Array.prototype.slice.call(headers);
…
> headers.map(function(el) { return el.textContent; })
["What does Array.prototype.slice.call() & wrapper.querySelectorAll() do?", …]
于 2013-09-30T16:29:46.257 回答
2

它从任何类似数组的东西创建一个数组(例如,具有 alength和名称如01等的属性)。你会看到很多getElementsByTagName这样的东西,它们会返回实时NodeList实例。真的没有必要querySelectorAll,因为这会返回非实时列表,除非你当然想要Array.

Array.prototype.slice.call(...)看起来有点吓人,但实际上很简单:数组从 object 获取方法Array.prototype。其中之一是slice返回数组一部分副本的方法。如果您不提供slice任何参数,它将返回整个数组的副本。但棘手的一点是,当您调用 时slice,您不必在数组上调用它,只需看起来像数组。在 JavaScript 中使用Function#call时,您可以设置this调用中的内容。所以Array.prototype.slice.call(resultFromQuerySelectorAll)调用slice结果this来自querySelectorAll; slice然后很乐意为您提供一个包含这些条目的数组。

于 2013-09-30T16:30:02.180 回答