简体   繁体   English

.slice(0) 在这里有什么意义?

[英]What's the point of .slice(0) here?

I was studying the jQuery source when I found this (v1.5 line 2295):当我发现这个时,我正在研究 jQuery 源代码(v1.5 第 2295 行):

namespace = new RegExp("(^|\\.)" +
  jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)");

My question is, why use slice(0) here?我的问题是,为什么在这里使用slice(0)

sort() modifies the array it's called on - and it isn't very nice to go around mutating stuff that other code might rely on. sort()修改了它被调用的数组 - 绕过改变其他代码可能依赖的东西并不是很好。

slice() always returns a new array - the array returned by slice(0) is identical to the input, which basically means it's a cheap way to duplicate an array. slice()总是返回一个新数组 - slice(0)返回的数组与输入相同,这基本上意味着它是复制数组的一种廉价方法。

arr.slice(0) makes a copy of the original array by taking a slice from the element at index 0 to the last element. arr.slice(0)通过从索引 0 处的元素到最后一个元素的切片来复制原始数组。

It was also used to convert array-like objects into arrays.它还用于将类似数组的对象转换为数组。 For example, a DOM NodeList (returned by several DOM methods like getElementsByTagName ) is not an array, but it is an array-like object with a length field and is indexable in JavaScript.例如,一个 DOM NodeList (由getElementsByTagName等几个 DOM 方法返回)不是一个数组,但它是一个具有length字段的类数组对象,并且在 JavaScript 中是可索引的。 To convert it to an array, one often used:要将其转换为数组,经常使用:

var anchorArray = [].slice.call(document.getElementsByTagName('a'), 0)

Now, ES2015's spread syntax is used to convert iterable objects, including NodeList and HTMLCollection , to arrays:现在,ES2015 的扩展语法用于将可迭代对象(包括NodeListHTMLCollection )转换为数组:

const anchorArray = [...document.getElementsByTagName('a')]

slice(0) creates a new array identical to the original array. slice(0)创建一个与原始数组相同的新数组。 Many times you want to preserve your original array and create a new one.很多时候,您想保留原始数组并创建一个新数组。

If you use slice(1) , it will create a different array starting from index position 1.如果您使用slice(1) ,它将从索引位置 1 开始创建一个不同的数组。

Similar things hold for strings as well.类似的事情也适用于字符串。

slice(0)允许您返回您正在引用的现有数组的数组,在本例中为命名空间。

In addition to what @Anon said:除了@Anon所说的:

The slice() method selects the elements starting at the given start argument, and ends at, but does not include, the given end argument. slice()方法选择从给定的 start 参数开始的元素,并在给定的 end 参数处结束,但不包括。

Example1:示例 1:

var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1, 3);

The result of citrus will be:柑橘的结果将是:

Orange,Lemon

Example2:示例 2:

var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(-3, -1);

The result of citrus will be:柑橘的结果将是:

Lemon,Apple

Further information can be found here .更多信息可以在这里找到。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM