array.copyWithin

array.copyWithin

copyWithin()方法将数组的一部分简单地复制到同一数组中的另一个位置,并将其返回,而不修改其大小。

['alpha', 'bravo', 'charlie', 'delta'].copyWithin(2, 0 // results in ["alpha", "bravo", "alpha", "bravo"]

语法

arr.copyWithin(target) arr.copyWithin(target, start) arr.copyWithin(target, start, end)

Parameters

target0 为基底的索引,复制序列到该位置。如果是负数,target 将从末尾开始计算。如果target大于等于arr.length,将会不发生拷贝。如果targetstart之后,复制的序列将被修改以符合arr.length

返回值

改变了的数组。

描述

copyWithin 就像 C 和 C++ 的 memcpy 函数一样,且它是用来移动Array或者 TypedArray数据的一个高性能的方法。复制以及粘贴序列这两者是为一体的操作;即使复制和粘贴区域重叠,粘贴的序列也会有拷贝来的值。

copyWithin函数是设计为通用的,其不要求其this值必须是一个数组对象。

The copyWithin 是一个可变方法,它不会改变 this的长度,但是会改变 this本身的内容,且需要时会创建新的属性。

示例

[1, 2, 3, 4, 5].copyWithin(-2 // [1, 2, 3, 1, 2] [1, 2, 3, 4, 5].copyWithin(0, 3 // [4, 5, 3, 4, 5] [1, 2, 3, 4, 5].copyWithin(0, 3, 4 // [4, 2, 3, 4, 5] [1, 2, 3, 4, 5].copyWithin(-2, -3, -1 // [1, 2, 3, 3, 4] [].copyWithin.call{length: 5, 3: 1}, 0, 3 // {0: 1, 3: 1, length: 5} // ES2015 Typed Arrays are subclasses of Array var i32a = new Int32Array([1, 2, 3, 4, 5] i32a.copyWithin(0, 2 // Int32Array [3, 4, 5, 4, 5] // On platforms that are not yet ES2015 compliant: [].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4 // Int32Array [4, 2, 3, 4, 5]

Polyfill

if (!Array.prototype.copyWithin) {   Array.prototype.copyWithin =   // Array: Number[, Number[, Number]]   function copyWithin(target, start, stop) {     var positiveT = target >= 0,         positiveS = (start = start | 0) >= 0,         length    = this.length,         zero      = 0,         r         = function() {return ((+new Date) * Math.random()).toString(36)},         delimiter = "\b" + r() + "-" + r() + "-" + r() + "\b",         hold;     stop = stop || this.length;     hold = this.slice.apply(this,       positiveT?         [start, stop]:       positiveS?         [start, -target]:       [start])     .join(delimiter     return this.splice.apply(this,       positiveT?         [target, stop - start, hold]:       positiveS?         [target, stop, hold]:       [target, start, hold]),             this.join(delimiter).split(delimiter).slice(zero, length   } }

规范

SpecificationStatusComment
ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'Array.prototype.copyWithin' in that specification.StandardInitial definition.
ECMAScript 2016 (ECMA-262)The definition of 'Array.prototype.copyWithin' in that specification.Standard
ECMAScript Latest Draft (ECMA-262)The definition of 'Array.prototype.copyWithin' in that specification.Living Standard

浏览器支持

FeatureChromeEdgeFirefoxInternet ExplorerOperaSafari
Basic Support451232未实现329

FeatureAndroidChrome for AndroidEdge mobileFirefox for AndroidIE mobileOpera AndroidiOS Safari
Basic Support(已实现)(已实现)(已实现)32未实现(已实现)(已实现)