aboutsummaryrefslogtreecommitdiff
path: root/files/nl/web/javascript/reference/global_objects/array/slice/index.html
blob: d3dcaf0acb0157b917994f6358242245577d0bea (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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
---
title: Array.prototype.slice()
slug: Web/JavaScript/Reference/Global_Objects/Array/slice
translation_of: Web/JavaScript/Reference/Global_Objects/Array/slice
---
<p>{{JSRef}}<br>
 De <code><strong>slice()</strong></code> method geeft een oppervlakkige kopie van een gedeelte van een array terug in een nieuwe array.</p>

<h2 id="Syntax">Syntax</h2>

<pre class="syntaxbox"><code><var>arr</var>.slice([<var>begin</var>[, <var>end</var>]])</code></pre>

<h2 id="Parameters">Parameters</h2>

<dl>
 <dt><code>begin</code></dt>
 <dd>Bij nul beginnende index (zero-based), van waaruit de extractie begint.</dd>
 <dd>Bij een negatieve index, geeft <code>begin</code> het aantal plaatsen (offset) tot aan het einde van de reeks. <code>slice(-2)</code> extraheert de laatste twee elementen van de sequentie.</dd>
 <dd>Indien <code>begin</code> niet gedefinieerd is, of gelijkwaardig is aan undefined, dan begint <code>slice</code> bij index <code>0</code>.</dd>
 <dt><code>end</code></dt>
 <dd>Bij nul beginnende index waarop de extractie gestopt wordt. <code>slice</code> extraheert tot aan, maar exclusief <code>end</code>.</dd>
 <dd><code>slice(1,4)</code> extraheert het tweede element tot het vierde element (elementen met index 1, 2, en 3).</dd>
 <dd>Als negatieve index, geeft <code>end</code> een afstand (offset) aan tot het einde van de reeks. <code>slice(2,-1)</code> extraheert het derde element tot het op twee na laatse element in de sequentie.</dd>
 <dd>Indien <code>end</code> wordt weggelaten, dan zal <code>slice</code> tot het einde van de reeks toe extraheren (<code>arr.length</code>)<code>.</code></dd>
</dl>

<h2 id="Beschrijving">Beschrijving</h2>

<p><code>slice</code> verandert niet. Het retourneert een oppervlakkige kopie van elementen, ten opzichte van de oorspronkelijke array. Elementen van het origineel, worden als volgt gekopieerd en geretourneerd:</p>

<ul>
 <li>Voor object referenties (en dus niet het eigenlijke object), kopieert <code>slice</code> object referenties naar een nieuwe array. Zowel het origineel als ook de nieuwe array verwijzen naar hetzelfde object. Indien een object, waarnaar verwezen wordt, verandert, dan zullen de wijzigingen zowel in de nieuwe als bestaande array zichtbaar worden.</li>
 <li>Voor strings en getallen (geen {{jsxref("String")}} en {{jsxref("Number")}} objects), kopieert <code>slice</code> strings en getallen naar de nieuwe array. Veranderingen aan een  string of getal in de ene array zal de andere array niet beinvloeden.</li>
</ul>

<p>Indien een nieuw element aan de ene array wordt toegevoegd, dan blijft de andere array onaangeroerd.</p>

<h2 id="Voorbeelden">Voorbeelden</h2>

<h3 id="Geeft_een_gedeelte_van_een_bestaande_array">Geeft een gedeelte van een bestaande array</h3>

<pre class="brush: js">var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
var citrus = fruits.slice(1, 3);

// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
// citrus contains ['Orange','Lemon']
</pre>

<h3 id="Gebruik_slice">Gebruik <code>slice</code></h3>

<p>In het volgende voorbeeld, maakt <code>slice</code> een nieuwe array aan, <code>newCar</code>, uit <code>myCar</code>. Beide hebben een referentie aan het object <code>myHonda</code>. Wanneer de kleur van <code>myHonda</code> wordt gewijzigd, dan hebben beide arrays deze wisseling ondergaan.</p>

<pre class="brush: js">// Using slice, create newCar from myCar.
var myHonda = { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } };
var myCar = [myHonda, 2, 'cherry condition', 'purchased 1997'];
var newCar = myCar.slice(0, 2);

// Display the values of myCar, newCar, and the color of myHonda
//  referenced from both arrays.
console.log('myCar = ' + myCar.toSource());
console.log('newCar = ' + newCar.toSource());
console.log('myCar[0].color = ' + myCar[0].color);
console.log('newCar[0].color = ' + newCar[0].color);

// Change the color of myHonda.
myHonda.color = 'purple';
console.log('The new color of my Honda is ' + myHonda.color);

// Display the color of myHonda referenced from both arrays.
console.log('myCar[0].color = ' + myCar[0].color);
console.log('newCar[0].color = ' + newCar[0].color);
</pre>

<p>Het script verwerkt dit als volgt:</p>

<pre class="brush: js">myCar = [{color:'red', wheels:4, engine:{cylinders:4, size:2.2}}, 2,
         'cherry condition', 'purchased 1997']
newCar = [{color:'red', wheels:4, engine:{cylinders:4, size:2.2}}, 2]
myCar[0].color = red
newCar[0].color = red
The new color of my Honda is purple
myCar[0].color = purple
newCar[0].color = purple
</pre>

<h2 id="Array-achtige_objecten">Array-achtige objecten</h2>

<p><code>De slice</code> method kan ook gebruikt worden om Array-like objects / collections om te zetten in een nieuwe Array. Je hoeft dan alleen de methode op zich aan het object te binden. De {{jsxref("Functions/arguments", "arguments")}} binnen een functie is een voorbeeld van een 'array-like object'.</p>

<pre class="brush: js">function list() {
  return Array.prototype.slice.call(arguments);
}

var list1 = list(1, 2, 3); // [1, 2, 3]
</pre>

<p>Binding kan worden verkregen met de  .<code>call</code> functie of {{jsxref("Function.prototype")}} en dit kan ook via reductie door gebruik te maken van <code>[].slice.call(arguments)</code> in plaats van de  <code>Array.prototype.slice.call</code>. Hoe dan ook, het kan worden vereenvoudigd met  {{jsxref("Function.prototype.bind", "bind")}}.</p>

<pre class="brush: js">var unboundSlice = Array.prototype.slice;
var slice = Function.prototype.call.bind(unboundSlice);

function list() {
  return slice(arguments);
}

var list1 = list(1, 2, 3); // [1, 2, 3]
</pre>

<h2 id="Cross-browser_gedrag_in_de_hand_werken">Cross-browser gedrag in de hand werken</h2>

<p>Host objecten zoals DOM-objecten, zijn volgens de spec niet verplicht zich te gedragen zoals in een Mozilla browser, wanneer een omzetting plaatsvindt volgens de Array.prototype.slice methode. IE browsers voor versie 9 doen dit bijvoorbeeld niet. De huidige browser versies van IE, Mozilla, Chrome, Safari en Opera ondersteunen het eerder beschreven oppervlakkige kopie ('shallow copy') gedrag en het is daarmee de-facto het standaard gedrag.<br>
 Door onderstaande code vooraf te laten gaan aan de eigen code, kun je het toch mogelijk maken dat een browser zich zoals je zou verwachten gaat gedragen en er verder geen afwijkende browser specifieke code gebruikt hoeft te worden.</p>

<pre class="brush: js">/**
 * Shim for "fixing" IE's lack of support (IE &lt; 9) for applying slice
 * on host objects like NamedNodeMap, NodeList, and HTMLCollection
 * (technically, since host objects have been implementation-dependent,
 * at least before ES6, IE hasn't needed to work this way).
 * Also works on strings, fixes IE &lt; 9 to allow an explicit undefined
 * for the 2nd argument (as in Firefox), and prevents errors when
 * called on other DOM objects.
 */
(function () {
  'use strict';
  var _slice = Array.prototype.slice;

  try {
    // Can't be used with DOM elements in IE &lt; 9
    _slice.call(document.documentElement);
  } catch (e) { // Fails in IE &lt; 9
    // This will work for genuine arrays, array-like objects,
    // NamedNodeMap (attributes, entities, notations),
    // NodeList (e.g., getElementsByTagName), HTMLCollection (e.g., childNodes),
    // and will not fail on other DOM objects (as do DOM elements in IE &lt; 9)
    Array.prototype.slice = function(begin, end) {
      // IE &lt; 9 gets unhappy with an undefined end argument
      end = (typeof end !== 'undefined') ? end : this.length;

      // For native Array objects, we use the native slice function
      if (Object.prototype.toString.call(this) === '[object Array]'){
        return _slice.call(this, begin, end);
      }

      // For array like object we handle it ourselves.
      var i, cloned = [],
        size, len = this.length;

      // Handle negative value for "begin"
      var start = begin || 0;
      start = (start &gt;= 0) ? start : Math.max(0, len + start);

      // Handle negative value for "end"
      var upTo = (typeof end == 'number') ? Math.min(end, len) : len;
      if (end &lt; 0) {
        upTo = len + end;
      }

      // Actual expected size of the slice
      size = upTo - start;

      if (size &gt; 0) {
        cloned = new Array(size);
        if (this.charAt) {
          for (i = 0; i &lt; size; i++) {
            cloned[i] = this.charAt(start + i);
          }
        } else {
          for (i = 0; i &lt; size; i++) {
            cloned[i] = this[start + i];
          }
        }
      }

      return cloned;
    };
  }
}());
</pre>

<h2 id="Specifications">Specifications</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
  <tr>
   <td>{{SpecName('ES3')}}</td>
   <td>{{Spec2('ES3')}}</td>
   <td>Initial definition. Implemented in JavaScript 1.2.</td>
  </tr>
  <tr>
   <td>{{SpecName('ES5.1', '#sec-15.4.4.10', 'Array.prototype.slice')}}</td>
   <td>{{Spec2('ES5.1')}}</td>
   <td></td>
  </tr>
  <tr>
   <td>{{SpecName('ES6', '#sec-array.prototype.slice', 'Array.prototype.slice')}}</td>
   <td>{{Spec2('ES6')}}</td>
   <td></td>
  </tr>
  <tr>
   <td>{{SpecName('ESDraft', '#sec-array.prototype.slice', 'Array.prototype.slice')}}</td>
   <td>{{Spec2('ESDraft')}}</td>
   <td></td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility">Browser compatibility</h2>

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

<div id="compat-desktop">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Chrome</th>
   <th>Firefox (Gecko)</th>
   <th>Internet Explorer</th>
   <th>Opera</th>
   <th>Safari</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatChrome("1.0")}}</td>
   <td>{{CompatGeckoDesktop("1.7")}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
  </tr>
 </tbody>
</table>
</div>

<div id="compat-mobile">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Android</th>
   <th>Chrome for Android</th>
   <th>Firefox Mobile (Gecko)</th>
   <th>IE Mobile</th>
   <th>Opera Mobile</th>
   <th>Safari Mobile</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
  </tr>
 </tbody>
</table>
</div>

<h2 id="See_also">See also</h2>

<ul>
 <li>{{jsxref("Function.prototype.call()")}}</li>
 <li>{{jsxref("Function.prototype.bind()")}}</li>
</ul>