javascript 中 [].slice.call 的解释?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2125714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Explanation of [].slice.call in javascript?
提问by Yansky
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 sliceis used to convert the result of callto a new array yeah?
所以它以一个空数组开始[],然后slice用于将结果转换call为一个新数组是吗?
The bit I don't understand is the call. How does that convert document.querySelectorAll('a')from a NodeList to a regular array?
我不明白的一点是call. 那如何document.querySelectorAll('a')从 NodeList 转换为常规数组?
采纳答案by Max Shawabkeh
What's happening here is that you call slice()as if it was a function of NodeListusing 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. Here's an article on this.
这里发生的事情是你调用slice()好像它是一个NodeListusing的函数call()。什么slice()做在这种情况下是通过运行它的对象(最初的数组,现在创建一个空数组,然后迭代NodeList),并保留追加该对象的元素,它创建的空数组,这是最终返回。这是一篇关于此的文章。
EDIT:
编辑:
So it starts with an empty array [], then slice is used to convert the result of call to a new array yeah?
所以它以一个空数组[]开头,然后切片用于将调用结果转换为新数组是吗?
That's not right. [].slicereturns a function object. A function object has a function call()which calls the function assigning the first parameter of the call()to this; in other words, making the function think that it's being called from the parameter (the NodeListreturned by document.querySelectorAll('a')) rather than from an array.
那是不对的。[].slice返回一个函数对象。一个函数对象有一个函数call(),它调用分配给call()to的第一个参数的函数this;换句话说,使函数认为它是从参数(由NodeList返回的document.querySelectorAll('a'))而不是从数组调用的。
回答by slebetman
In JavaScript, methods of an object can be bound to another object at runtime. In short, javascript allows an object to "borrow" the method of another object:
在 JavaScript 中,一个对象的方法可以在运行时绑定到另一个对象。简而言之,javascript 允许一个对象“借用”另一个对象的方法:
object1 = {
name: 'Frank',
greet() {
alert(`Hello ${this.name}`);
}
};
object2 = {
name: 'Andy'
};
// Note that object2 has no greet method,
// but we may "borrow" from object1:
object1.greet.call(object2); // Will show an alert with 'Hello Andy'
The calland applymethods of function objects (in JavaScript, functions are objects as well) allows you to do this. So, in your code you could say that the NodeList is borrowing an array's slice method. .slice()returns another array as its result, which will become the "converted" array that you can then use.
函数对象的call和apply方法(在 JavaScript 中,函数也是对象)允许您这样做。因此,在您的代码中,您可以说 NodeList 借用了数组的 slice 方法。.slice()返回另一个数组作为其结果,它将成为您可以使用的“转换后”数组。
回答by Brian Campbell
It retrieves the slicefunction from an Array. It then calls that function, but using the result of document.querySelectorAllas the thisobject instead of an actual array.
它slice从Array. 然后它调用该函数,但使用 的结果document.querySelectorAll作为this对象而不是实际数组。
回答by Gras Double
It is a technique to convert array-like objects to real arrays.
它是一种将类数组对象转换为真实数组的技术。
Some of these objects include:
其中一些对象包括:
argumentsin functions- NodeList(remember their content can change after being fetched! so converting them to array is a way to freeze them)
- jQuery collections, aka jQuery objects (some doc: API, type, learn)
arguments在函数中- NodeList(记住它们的内容在被获取后可以改变!所以将它们转换为数组是一种冻结它们的方法)
- jQuery 集合,又名 jQuery 对象(一些文档:API、type、learn)
This serves many purposes, for example objects are passed by reference whereas arrays are passed by value.
这有很多用途,例如对象通过引用传递而数组通过值传递。
Also, note the first argument 0can be omited, thorough explanation here.
另外,注意第一个参数0可以省略,这里有详尽的解释。
And for the sake of completeness, there is also jQuery.makeArray().
为了完整起见,还有jQuery.makeArray()。
回答by Rajaprabhu Aravindasamy
How does that convert
document.querySelectorAll('a')from aNodeListto a regular array?
那如何
document.querySelectorAll('a')从 a 转换NodeList为常规数组?
This is the code that we have,
这是我们拥有的代码,
[].slice.call(document.querySelectorAll('a'), 0)
Lets dismantle it first,
先拆开看看
[] // Array object
.slice // Accessing the function 'slice' present in the prototype of Array
.call // Accessing the function 'call' present in the prototype of function object(slice)
(document.querySelectorAll('a'),0)
// 'call' can have arguments like, (thisArg, arg1,arg2...n).
// So here we are passing the 'thisArg' as an array like object,
// that is a 'nodeList'. It will be served as 'this' object inside of slice function.
// And finally setting 'start' argument of slice as '0' and leaving the 'end'
// argument as 'undefined'
Step: 1 Execution of callfunction
步骤:1 执行call函数
- Inside
call, other than thethisArg, the rest of the arguments will be appended to an argument list. - Now the function
slicewill be invoked by binding itsthisvalue asthisArg(array like object came fromdocument.querySelector) and with the argument list. i.e] argumentstartwhich contains0
- 在里面
call,除了thisArg,其余的参数将被附加到一个参数列表中。 - 现在,该函数
slice将通过将其this值绑定为thisArg(类似数组的对象来自document.querySelector)和参数列表来调用。即]start包含的参数0
Step: 2 Execution of slicefunction invoked inside of call
步骤:2 执行slice内部调用的函数call
startwill be assigned to a variablesas0- since
endisundefined,this.lengthwill be stored ine - an empty array will be stored in a variable
a After making the above settings the following iteration will be happened
while(s < e) { a.push(this[s]); s++; }- the filled up array
awill be returned as the result.
start将被分配给一个变量s作为0- 因为
end是undefined,this.length将被存储在e - 一个空数组将存储在一个变量中
a 进行上述设置后,将进行以下迭代
while(s < e) { a.push(this[s]); s++; }- 填充的数组
a将作为结果返回。
P.S For better understanding of our scenario some steps that are necessary for our context has been ignored from the original algorithm of calland slice.
回答by Ankit Parmar
[].slice.call(document.querySelectorAll('.slide'));
1. The querySelectorAll() method returns all elements in the document that matches a specified selector(s).
2. The call() method calls a function with a given this value and arguments provided individually.
3. The slice() method returns the selected elements in an array, as a new array object.
so this line return the array of [object HTMLDivElement]. Here is the six div with classname "slide" so array length will be 6.
<div class="slideshow">
<div class="slide">
first slider1
</div>
<div class="slide">
first slider2
</div>
<div class="slide">
first slider3
</div>
<div class="slide">
first slider4
</div>
<div class="slide">
first slider5
</div>
<div class="slide">
first slider6
</div>
</div>
<script type="text/javascript">
var arraylist = [].slice.call(document.querySelectorAll('.slide'));
alert(arraylist);
</script>
回答by Мони
From ES6: Simply make array with Array.from(element.children)or Array.from({length: 5})
从 ES6:简单地使用Array.from(element.children)或Array.from({length: 5})创建数组

