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

前端 未结 5 813
后悔当初
后悔当初 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: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)
    

提交回复
热议问题