且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-09-13 11:54:42

这个***链接里有详细讨论。

https://***.com/questions/5024085/whats-the-point-of-slice0-here很多高手的JavaScript代码里都有array.slice(0),这语句有什么用其他热心网友的解释是:对数组施加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:

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