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
301 views
in Technique[技术] by (71.8m points)

javascript - 在JavaScript中解释[] .slice.call?(Explanation of [].slice.call in javascript?)

I stumbled onto this neat shortcut for converting a DOM NodeList into a regular array, but I must admit, I don't completely understand how it works:(我偶然发现了将DOM NodeList转换为常规数组的简洁快捷方式,但我必须承认,我并不完全理解它是如何工作的:)

[].slice.call(document.querySelectorAll('a'), 0) So it starts with an empty array [] , then slice is used to convert the result of call to a new array yeah?(所以它以空数组[]开头,然后使用slicecall结果转换为新数组是啊?) The bit I don't understand is the call .(我不明白的是call 。) How does that convert document.querySelectorAll('a') from a NodeList to a regular array?(如何将document.querySelectorAll('a')从NodeList转换为常规数组?)   ask by Yansky translate from so

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

1 Reply

0 votes
by (71.8m points)

What's happening here is that you call slice() as if it was a function of NodeList using call() .(这里发生的事情是,你调用slice() ,如果它是一个功能NodeList使用call() 。)

What slice() does in this case is create an empty array, then iterate through the object it's running on (originally an array, now a NodeList ) and keep appending the elements of that object to the empty array it created, which is eventually returned.(在这种情况下slice()作用是创建一个空数组,然后遍历它运行的对象(最初是一个数组,现在是一个NodeList )并继续将该对象的元素追加到它创建的空数组中,最后返回。) Here's an article on this .(这是一篇关于此文章 。) EDIT:(编辑:) So it starts with an empty array [], then slice is used to convert the result of call to a new array yeah?(所以它以空数组[]开头,然后使用slice将调用结果转换为新数组是啊?) That's not right.(那是不对的。) [].slice returns a function object.([].slice返回一个函数对象。) A function object has a function call() which calls the function assigning the first parameter of the call() to this ;(函数对象有一个函数call() ,它调用函数将call()的第一个参数赋给this ;) in other words, making the function think that it's being called from the parameter (the NodeList returned by document.querySelectorAll('a') ) rather than from an array.(换句话说,使函数认为它是从参数( document.querySelectorAll('a')返回的NodeList )而不是从数组中调用的。)

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

...