aboutsummaryrefslogtreecommitdiff
path: root/files/ru/web/javascript/reference/global_objects/array/copywithin/index.html
blob: 7b46ef0a680a4dd903941c2d4c2c3821a5735bc1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
---
title: Array.prototype.copyWithin()
slug: Web/JavaScript/Reference/Global_Objects/Array/copyWithin
tags:
  - Array
  - ECMAScript6
  - Experimental
  - JavaScript
  - Method
  - Prototype
  - Reference
  - polyfill
translation_of: Web/JavaScript/Reference/Global_Objects/Array/copyWithin
---
<div>{{JSRef("Global_Objects", "Array")}}</div>

<h2 id="Summary" name="Summary">Сводка</h2>

<p>Метод <code><strong>copyWithin()</strong></code> копирует последовательность элементов массива внутри него в позицию, начинающуюся по индексу <code>target</code>. Копия берётся по индексам, задаваемым вторым и третьим аргументами <code>start</code> и <code>end</code>. Аргумент <code>end</code> является необязательным и по умолчанию равен длине массива.</p>

<h2 id="Syntax" name="Syntax">Синтаксис</h2>

<pre class="syntaxbox"><code><var>arr</var>.copyWithin(<var>target</var>, <var>start</var>[, <var>end</var> = this.length])</code></pre>

<h3 id="Parameters" name="Parameters">Параметры</h3>

<dl>
 <dt><code>target</code></dt>
 <dd>Начальный индекс позиции цели, куда копировать элементы.</dd>
 <dt><code>start</code></dt>
 <dd>Начальный индекс позиции источника, откуда начинать копировать элементы.</dd>
 <dt><code>end</code></dt>
 <dd>Необязательный параметр. Конечный индекс позиции источника, где заканчивать копировать элементы.</dd>
</dl>

<h2 id="Description" name="Description">Описание</h2>

<p>Аргументы <code>target</code>, <code>start</code> и <code>end</code> приводятся к {{jsxref("Global_Objects/Number", "Number")}} и обрезаются до целых значений.</p>

<p>Если аргумент <code>start</code> является отрицательным, он трактуется как <code>length+start</code> где <code>length</code> — это длина массива. Если аргумент <code>end</code> является отрицательным, он трактуется как <code>length+end</code>.</p>

<p>Функция <code>copyWithin</code> намеренно является <em>обобщённой</em>, она не требует, чтобы значение <code>this</code> внутри неё было объектом {{jsxref("Global_Objects/Array", "Array")}}, и кроме того, функция <code>copyWithin</code> является <em>изменяющим методом</em>, она изменит объект <code>this</code> и вернёт его, а не просто вернёт копию.</p>

<h2 id="Examples" name="Examples">Примеры</h2>

<pre class="brush: js">[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(0, -2, -1);
// [4, 2, 3, 4, 5]

[].copyWithin.call({length: 5, 3: 1}, 0, 3);
// {0: 1, 3: 1, length: 5}

// Типизированные массивы ES6 являются подклассами Array
var i32a = new Int32Array([1, 2, 3, 4, 5]);

i32a.copyWithin(0, 2);
// Int32Array [3, 4, 5, 4, 5]

// На платформах, которые ещё не совместимы с ES6:
[].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4);
// Int32Array [4, 2, 3, 4, 5]
</pre>

<h2 id="Polyfill" name="Polyfill">Полифил</h2>

<pre class="brush: js">if (!Array.prototype.copyWithin) {
  Array.prototype.copyWithin = function(target, start/*, end*/) {
    // Шаги 1-2.
    if (this == null) {
      throw new TypeError('this is null or not defined');
    }

    var O = Object(this);

    // Шаги 3-5.
    var len = O.length &gt;&gt;&gt; 0;

    // Шаги 6-8.
    var relativeTarget = target &gt;&gt; 0;

    var to = relativeTarget &lt; 0 ?
      Math.max(len + relativeTarget, 0) :
      Math.min(relativeTarget, len);

    // Шаги 9-11.
    var relativeStart = start &gt;&gt; 0;

    var from = relativeStart &lt; 0 ?
      Math.max(len + relativeStart, 0) :
      Math.min(relativeStart, len);

    // Шаги 12-14.
    var end = arguments[2];
    var relativeEnd = end === undefined ? len : end &gt;&gt; 0;

    var final = relativeEnd &lt; 0 ?
      Math.max(len + relativeEnd, 0) :
      Math.min(relativeEnd, len);

    // Шаг 15.
    var count = Math.min(final - from, len - to);

    // Шаги 16-17.
    var direction = 1;

    if (from &lt; to &amp;&amp; to &lt; (from + count)) {
      direction = -1;
      from += count - 1;
      to += count - 1;
    }

    // Шаг 18
    while (count &gt; 0) {
      if (from in O) {
        O[to] = O[from];
      } else {
        delete O[to];
      }

      from += direction;
      to += direction;
      count--;
    }

    // Шаг 19.
    return O;
  };
}
</pre>

<h2 id="Specifications" name="Specifications">Спецификации</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Спецификация</th>
   <th scope="col">Статус</th>
   <th scope="col">Комментарии</th>
  </tr>
  <tr>
   <td>{{SpecName('ES6', '#sec-array.prototype.copyWithin', 'Array.prototype.copyWithin')}}</td>
   <td>{{Spec2('ES6')}}</td>
   <td>Изначальное определение.</td>
  </tr>
  <tr>
   <td>{{SpecName('ESDraft', '#sec-array.prototype.copyWithin', 'Array.prototype.copyWithin')}}</td>
   <td>{{Spec2('ESDraft')}}</td>
   <td> </td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility" name="Browser_compatibility">Совместимость с браузерами</h2>

<div>{{CompatibilityTable}}</div>

<div id="compat-desktop">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Возможность</th>
   <th>Chrome</th>
   <th>Firefox (Gecko)</th>
   <th>Internet Explorer</th>
   <th>Edge</th>
   <th>Opera</th>
   <th>Safari</th>
  </tr>
  <tr>
   <td>Базовая поддержка</td>
   <td>{{CompatChrome("45")}}</td>
   <td>{{CompatGeckoDesktop("32")}}</td>
   <td>{{CompatNo}}</td>
   <td>12</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
  </tr>
 </tbody>
</table>
</div>

<div id="compat-mobile">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Возможность</th>
   <th>Android</th>
   <th>Chrome для Android</th>
   <th>Firefox Mobile (Gecko)</th>
   <th>IE Mobile</th>
   <th>Opera Mobile</th>
   <th>Safari Mobile</th>
  </tr>
  <tr>
   <td>Базовая поддержка</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatGeckoMobile("32")}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
  </tr>
 </tbody>
</table>
</div>

<h2 id="See_also" name="See_also">Смотрите также</h2>

<ul>
 <li>{{jsxref("Global_Objects/Array", "Array")}}</li>
</ul>