JS slice()

🌙
手机阅读
本文目录结构

**slice()**方法返回一个typed array的部分类型数组对象,数组内容采用浅拷贝方式. 方法采用与 Array.prototype.slice()相同的算法_._ _类型数组_是 typed array types成员中的一员 .

语法

typedarray.slice([begin[, end]])

参数列表

begin:起始位置 可选

从0开始的索引位置;

负值索引, 表示与数组尾元素的偏移量. slice(-2) 表示提取数列中的末尾两个元素.

如果没有设定起始位置,则将从开始位置开始截取。

end:结束位置 可选

从零开始到尾元素前的索引值. slice 取出元素时包含起始节点,单不包含结束节点。

例, slice(1,4) 表示读取第二个元素到第四个元素(元素索引位置:1, 2, and 3).

负值索引, 表示与数组尾元素的偏移量。 slice(2,-1) 表示取出数组中的第三个到最后一个之间的所有元素.

如果没有设定结束位置,则将从开始位置截取到序列尾部。(typedarray.length).

返回值

包含取出元素的新的 typed array

Description

slice方法并不会改变原数组的内容,他只是返回从原数组中取出的元素的浅复制集合。

如何一个新元素被添加到任何一个数组中去,则另外一个数组不会发生变化。

Examples

返回已存在类型数组的部分片段

var uint8 = new Uint8Array([1,2,3]);
uint8.slice(1);   // Uint8Array [ 2, 3 ]
uint8.slice(2);   // Uint8Array [ 3 ]
uint8.slice(-2);  // Uint8Array [ 2, 3 ]
uint8.slice(0,1); // Uint8Array [ 1 ]

Polyfill

Since there is no global object with the name TypedArray, polyfilling must be done on an “as needed” basis.

// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.slice
if (!Uint8Array.prototype.slice) {
  Object.defineProperty(Uint8Array.prototype, 'slice', {
    value: Array.prototype.slice
  });
}

This is not a complete polyfill, since it returns an instance of Array, and not Uint8Array, so it lacks properties that would normally exist on TypedArrays.

If you need to support truly obsolete JavaScript engines that don’t support [Object.defineProperty], it’s best not to polyfill Array.prototype methods at all, as you can’t make them non-enumerable.

Specifications

Specification Status Comment
[ECMAScript 2015 (6th Edition, ECMA-262)
%TypedArray%.prototype.slice](https://www.ecma-international.org/ecma-262/6.0/#sec-%typedarray%.prototype.slice) Standard Initial definition.
[ECMAScript Latest Draft (ECMA-262)
%TypedArray%.prototype.slice](https://tc39.es/ecma262/#sec-%typedarray%.prototype.slice) Draft  

Browser compatibility

The compatibility table on this page is generated from structured data. If you’d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

Update compatibility data on GitHub

Desktop Mobile Server
Chrome Edge Firefox
slice Chrome Full support 45 Edge Full support 14 Firefox Full support 38

Legend

Full support  

Full support

No support  

No support

Compatibility unknown  

Compatibility unknown

See also

AXIHE / 精选资源

浏览全部教程

面试题

学习网站

前端培训
自己甄别

前端书籍

关于朱安邦

我叫 朱安邦,阿西河的站长,在杭州。

以前是一名平面设计师,后来开始接接触前端开发,主要研究前端技术中的JS方向。

业余时间我喜欢分享和交流自己的技术,欢迎大家关注我的 Bilibili

关注我: Github / 知乎

于2021年离开前端领域,目前重心放在研究区块链上面了

我叫朱安邦,阿西河的站长

目前在杭州从事区块链周边的开发工作,机械专业,以前从事平面设计工作。

2014年底脱产在老家自学6个月的前端技术,自学期间几乎从未出过家门,最终找到了满意的前端工作。更多>

于2021年离开前端领域,目前从事区块链方面工作了