aboutsummaryrefslogtreecommitdiff
path: root/files/uk/web/javascript/reference/global_objects/array/copywithin/index.html
blob: b2d5e837e2e951d07d9dbb60886bcd4eaa64a293 (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
---
title: Array.prototype.copyWithin()
slug: Web/JavaScript/Reference/Global_Objects/Array/copyWithin
tags:
  - ECMAScript 2015
  - JavaScript
  - Масив
  - метод
  - прототип
translation_of: Web/JavaScript/Reference/Global_Objects/Array/copyWithin
---
<div>{{JSRef}}</div>

<p>Метод <code><strong>copyWithin()</strong></code> додає дрібну копію частини масиву в іншу позицію в тому ж масиві та повертає його без зміни довжини.</p>

<div>{{EmbedInteractiveExample("pages/js/array-copywithin.html")}}</div>



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

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

<h3 id="Параметри">Параметри</h3>

<dl>
 <dt><code>target</code></dt>
 <dd>Індекс (нумерується з 0), куди потрібно скопіювати послідовність. Якщо індекс є від'ємним, <code>target</code> буде рахуватися з кінця масиву.</dd>
 <dd>Якщо значення <code>target</code> дорівнює або більше за <code>arr.length</code>, нічого не скопіюється. Якщо індекс <code>target</code> більший за <code>start</code>, скопійована послідовність буде обрізана відповідно до <code>arr.length</code>.</dd>
 <dt><code>start</code> {{optional_inline}}</dt>
 <dd>Індекс (нумерується з 0), з якого потрібно починати копіювання елементів. Якщо він від'ємний, <code>start</code> буде рахуватися з кінця.</dd>
 <dd>Якщо параметр <code>start</code> не заданий, <code>copyWithin</code> буде копіювати, починаючи з індекса 0. </dd>
 <dt><code>end</code> {{optional_inline}}</dt>
 <dd>Індекс (нумерується з 0), на якому потрібно закінчити копіювання елементів. <code>copyWithin</code> копіює до, але не включаючи, <code>end</code>. Якщо індекс від'ємний, <code>end</code> буде рахуватися з кінця.</dd>
 <dd>Якщо параметр <code>end</code> не заданий, <code>copyWithin</code> буде копіювати до останнього індекса (за замовченням <code>arr.length</code>).</dd>
</dl>

<h3 id="Значення_яке_повертається">Значення, яке повертається</h3>

<p>Змінений масив.</p>

<h2 id="Опис">Опис</h2>

<p>Метод <code>copyWithin</code> працює, як <code>memmove</code> у C та C++, і є дуже продуктивним методом для зсунення даних у {{jsxref("Array", "масиві")}}. Це особливо стосується метода {{jsxref("TypedArray/copyWithin", "TypedArray")}} з такою ж самою назвою. Послідовність копіюється та вставляється однією операцією; вставлена послідовність міститиме скопійовані значення, навіть коли ділянки копіювання та вставки накладаються.</p>

<p>Функція <code>copyWithin</code> є навмисно <em>загальною</em>, вона не вимагає, щоб її <code>this</code> був об'єктом {{jsxref("Array")}}.</p>

<p>Метод <code>copyWithin</code> є методом модифікації. Він не змінює довжину об'єкта <code>this</code>, але він змінює його зміст та створює нові властивості в разі необхідності.</p>

<h2 id="Приклади">Приклади</h2>

<pre class="brush: js">[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 типізовані масиви є підкласами Array
var i32a = new Int32Array([1, 2, 3, 4, 5]);

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

// На платформах, які ще не сумісні з ES2015:
[].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4);
// Int32Array [4, 2, 3, 4, 5]
</pre>

<h2 id="Поліфіл">Поліфіл</h2>

<pre class="brush: js">if (!Array.prototype.copyWithin) {
  Object.defineProperty(Array.prototype, 'copyWithin', {
    value: 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;
  },
  configurable: true,
  writable: true
  });
}</pre>

<h2 id="Специфікації">Специфікації</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Специфікація</th>
   <th scope="col">Статус</th>
   <th scope="col">Коментар</th>
  </tr>
  <tr>
   <td>{{SpecName('ES2015', '#sec-array.prototype.copywithin', 'Array.prototype.copyWithin')}}</td>
   <td>{{Spec2('ES2015')}}</td>
   <td>Початкове визначення.</td>
  </tr>
  <tr>
   <td>{{SpecName('ES2016', '#sec-array.prototype.copywithin', 'Array.prototype.copyWithin')}}</td>
   <td>{{Spec2('ES2016')}}</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="Сумісність_з_веб-переглядачами">Сумісність з веб-переглядачами</h2>

<div>


<p>{{Compat("javascript.builtins.Array.copyWithin")}}</p>
</div>

<h2 id="Див._також">Див. також</h2>

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