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

前端 未结 5 811
后悔当初
后悔当初 2020-12-23 18:31

I was studying the jQuery source when I found this (v1.5 line 2295):

namespace = new RegExp(\"(^|\\\\.)\" +
  jQuery.map( namespaces.slice(0).sort(), fcleanu         


        
相关标签:
5条回答
  • 2020-12-23 19:12

    slice(0) creates a new array identical to the original array. Many a 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.

    Similar things holds for strings as well.

    0 讨论(0)
  • 2020-12-23 19:22

    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.

    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.

    0 讨论(0)
  • 2020-12-23 19:24

    In addition to what @Anon said:

    The slice() method selects the elements starting at the given start argument, and ends at, but does not include, the given end argument.

    Example1:

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

    The result of citrus will be:

    Orange,Lemon
    

    Example2:

    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.

    0 讨论(0)
  • 2020-12-23 19:29

    arr.slice(0) makes a copy of the original array by taking a slice from the element at index 0 to the last element.

    It's 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. To convert it to an array, one often uses:

    var anchorArray = [].slice.call(document.getElementsByTagName('a'), 0)
    
    0 讨论(0)
  • 2020-12-23 19:29

    slice(0) allows you to return an array of the existing array you're referencing, in this case namespaces.

    0 讨论(0)
提交回复
热议问题