Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
802 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...