Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Revision 1083288 of Array.prototype.slice()

  • Revision slug: Web/JavaScript/Reference/Global_Objects/Array/slice
  • Revision title: Array.prototype.slice()
  • Revision id: 1083288
  • Created:
  • Creator: RdV
  • Is current revision? No
  • Comment

Revision Content

{{JSRef}}

De slice() method geeft een oppervlakkige kopie van een gedeelte van een array terug als een nieuwe array.

Syntax

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

Parameters

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

Beschrijving

slice verandert niet. Het retourneerd een oppervlakkige kopie van elementen, ten opzichte van de oorspronkelijke array. Elementen van het origineel, worden als volgt gekopieerd en geretourneerd:

  • Voor object referenties (en dus niet het eigenlijke object), kopieert slice object referenties naar een nieuwe array. Zowel het origineel als wel 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.
  • Voor strings en getallen (not {{jsxref("String")}} and {{jsxref("Number")}} objects), kopieert slice strings en getallen naar de nieuwe array. Veranderingen aan een  string of getal in de ene array zal de andere array niet beinvloeden.

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

Examples

Return a portion of an existing array

var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
var citrus = fruits.slice(1, 3);

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

Using slice

In the following example, slice creates a new array, newCar, from myCar. Both include a reference to the object myHonda. When the color of myHonda is changed to purple, both arrays reflect the change.

// 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);

This script writes:

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

Array-like objects

slice method can also be called to convert Array-like objects / collections to a new Array. You just bind the method to the object. The {{jsxref("Functions/arguments", "arguments")}} inside a function is an example of an 'array-like object'.

function list() {
  return Array.prototype.slice.call(arguments);
}

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

Binding can be done with the .call function of {{jsxref("Function.prototype")}} and it can also be reduced using [].slice.call(arguments) instead of Array.prototype.slice.call. Anyway, it can be simplified using {{jsxref("Function.prototype.bind", "bind")}}.

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]

Streamlining cross-browser behavior

Although host objects (such as DOM objects) are not required by spec to follow the Mozilla behavior when converted by Array.prototype.slice and IE < 9 does not do so, versions of IE starting with version 9 do allow this, “shimming” it can allow reliable cross-browser behavior. As long as other modern browsers continue to support this ability, as currently do IE, Mozilla, Chrome, Safari, and Opera, developers reading (DOM-supporting) slice code relying on this shim will not be misled by the semantics; they can safely rely on the semantics to provide the now apparently de facto standard behavior. (The shim also fixes IE to work with the second argument of slice() being an explicit {{jsxref("null")}}/{{jsxref("undefined")}} value as earlier versions of IE also did not allow but all modern browsers, including IE >= 9, now do.)

/**
 * Shim for "fixing" IE's lack of support (IE < 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 < 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 < 9
    _slice.call(document.documentElement);
  } catch (e) { // Fails in IE < 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 < 9)
    Array.prototype.slice = function(begin, end) {
      // IE < 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 >= 0) ? start : Math.max(0, len + start);

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

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

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

      return cloned;
    };
  }
}());

Specifications

Specification Status Comment
{{SpecName('ES3')}} {{Spec2('ES3')}} Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.10', 'Array.prototype.slice')}} {{Spec2('ES5.1')}}  
{{SpecName('ES6', '#sec-array.prototype.slice', 'Array.prototype.slice')}} {{Spec2('ES6')}}  
{{SpecName('ESDraft', '#sec-array.prototype.slice', 'Array.prototype.slice')}} {{Spec2('ESDraft')}}  

Browser compatibility

{{CompatibilityTable}}
Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support {{CompatChrome("1.0")}} {{CompatGeckoDesktop("1.7")}} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}}
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatVersionUnknown}}

See also

  • {{jsxref("Function.prototype.call()")}}
  • {{jsxref("Function.prototype.bind()")}}

Revision Source

<div>{{JSRef}}</div>

<p>De <code><strong>slice()</strong></code> method geeft een oppervlakkige kopie van een gedeelte van een array terug als 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 gedefinieert is, of gelijkwaardig is aan undefined, dan begint <code>slice</code> bij index <code>0</code>.</dd>
	<dt><code>end</code></dt>
	<dd>Vanuit nul beginnend te tellen 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="Description">Beschrijving</h2>

<p><code>slice</code> verandert niet. Het retourneerd 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 wel 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 (not {{jsxref("String")}} and {{jsxref("Number")}} objects), kopieert <code>slice</code> strings en getallen naar de nieuwe array. Veranderingen aan een&nbsp; 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="Examples">Examples</h2>

<h3 id="Return_a_portion_of_an_existing_array">Return a portion of an existing 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="Using_slice">Using <code>slice</code></h3>

<p>In the following example, <code>slice</code> creates a new array, <code>newCar</code>, from <code>myCar</code>. Both include a reference to the object <code>myHonda</code>. When the color of <code>myHonda</code> is changed to purple, both arrays reflect the change.</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>This script writes:</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-like_objects">Array-like objects</h2>

<p><code>slice</code> method can also be called to convert Array-like objects / collections to a new Array. You just bind the method to the object. The {{jsxref("Functions/arguments", "arguments")}} inside a function is an example of an '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 can be done with the .<code>call</code> function of {{jsxref("Function.prototype")}} and it can also be reduced using <code>[].slice.call(arguments)</code> instead of <code>Array.prototype.slice.call</code>. Anyway, it can be simplified using {{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="Streamlining_cross-browser_behavior">Streamlining cross-browser behavior</h2>

<p>Although host objects (such as DOM objects) are not required by spec to follow the Mozilla behavior when converted by <code>Array.prototype.slice</code> and IE &lt; 9 does not do so, versions of IE starting with version 9 do allow this, “shimming” it can allow reliable cross-browser behavior. As long as other modern browsers continue to support this ability, as currently do IE, Mozilla, Chrome, Safari, and Opera, developers reading (DOM-supporting) slice code relying on this shim will not be misled by the semantics; they can safely rely on the semantics to provide the now apparently <em>de facto</em> standard behavior. (The shim also fixes IE to work with the second argument of <code>slice()</code> being an explicit {{jsxref("null")}}/{{jsxref("undefined")}} value as earlier versions of IE also did not allow but all modern browsers, including IE &gt;= 9, now do.)</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>&nbsp;</td>
		</tr>
		<tr>
			<td>{{SpecName('ES6', '#sec-array.prototype.slice', 'Array.prototype.slice')}}</td>
			<td>{{Spec2('ES6')}}</td>
			<td>&nbsp;</td>
		</tr>
		<tr>
			<td>{{SpecName('ESDraft', '#sec-array.prototype.slice', 'Array.prototype.slice')}}</td>
			<td>{{Spec2('ESDraft')}}</td>
			<td>&nbsp;</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>
Revert to this revision