很多高手的JavaScript代码里都有array.slice(0),这语句有什么用

版权声明:本文为博主汪子熙原创文章,未经博主允许不得转载。 https://blog.csdn.net/i042416/article/details/89398655

这个stackoverflow链接里有详细讨论。
https://stackoverflow.com/questions/5024085/whats-the-point-of-slice0-here

clipboard1

一个网友在学习jQuery源代码时,对下面一行代码产生了疑惑:

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

clipboard2

其他热心网友的解释是:对数组施加sort操作,会修改调用sort的数据内元素的原始位置。因此为了保证不对sort方法调用的原数组产生副作用(side effect),我们使用slice(0)对原始数组进行一个深拷贝:

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另一种很有用的做法是将类数组对象转化为真正的数组对象。所谓类数组对象,一个例子就是API document.getElementsByTagName返回的结果NodeList的类型:虽然不是真正的数组,但是有length属性,支持用JavaScript按照索引访问每个元素。
使用var anchorArray = [].slice.call(document.getElementsByTagName(‘a’), 0)这种乾坤大挪移的办法,借用了[]这个原生数组提供的slice方法,可以轻松把NodeList转换成真正的JavaScript数组。

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)

clipboard3

clipboard4

要获取更多Jerry的原创文章,请关注公众号"汪子熙":

猜你喜欢

转载自blog.csdn.net/i042416/article/details/89398655