Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
796 views
in Technique[技术] by (71.8m points)

javascript - What does Array.prototype.slice.call() & wrapper.querySelectorAll() do?

I found following cone in a js plugin

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' ) );

I couldn't understand what does Array.prototype.slice.call() & wrapper.querySelectorAll( 'section' ) do in above code. I've not seen them before so I would like to know what they actually do.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

querySelectorAll is a method on DOM elements that accepts a CSS selector and returns a static NodeList of matching elements.

Array.prototype.slice.call is one way to turn that NodeList (which acts like an array, but doesn’t have the methods from Array.prototype) into a real array.

Give it a try on this page in your browser’s console!

> 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?", …]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...