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

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

提交回复
热议问题