--- title: Array.prototype.slice() slug: Web/JavaScript/Reference/Global_Objects/Array/slice translation_of: Web/JavaScript/Reference/Global_Objects/Array/slice ---
Il metodo slice()
ritorna la copia di una porzione dell'array contenente gli elementi compresi tra inzio
e fine
(fine
escluso). Il metodo slice() ritorna la copia dell'intero array se non contiene gli elementi di inizio e fine. L'array di partenza non viene modificato.
var a = ['zero', 'one', 'two', 'three']; var sliced = a.slice(1, 3); console.log(a); // ['zero', 'one', 'two', 'three'] console.log(sliced); // ['one', 'two']
arr.slice() arr.slice(inizio) arr.slice(inizio, fine)
begin
{{optional_inline}}slice(-2)
seleziona gli ultimi due elementi della sequenza.begin
non viene impostato , slice
parte dall'indice 0
.end
{{optional_inline}}slice
seleziona gli elementi fino a quell'indice ma non l'elemento all'indice end
.slice(1,4)
estrae dal secondo elemento dell'array al quarto escluso (elementi con indice 1, 2 e 3).slice(2,-1)
estrae dal terzo elemento della sequenza al penuntimo.end
non viene impostato, slice
continua l'estrazione sino al termine dell'array (arr.length
).end
è maggiore della lunghezza della sequenza , slice
continua l'estrazione sino al termine dell'array (arr.length
).Un nuovo array che contiene gli elementi estratti.
slice
non modifica l'array originale. Restituisce una copia superficiale degli elementi dell'array originale. Gli elementi dell'array originale vengono copiati nell'array restituito come segue:
slice
copia i riferimenti nel nuovo array. Entrambi gli array riferiscono quindi lo stesso oggetto. Se un oggetto riferito viene modificato, le modifiche interessano entrambi gli array.slice
copia i valori nel nuovo array. Le modifiche alle stringhe, ai numeri e ai boolean in un array non interessano l'altro array.Se viene aggiunto un nuovo elemento in uno degli array, l'altro non viene modificato.
var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']; var citrus = fruits.slice(1, 3); // fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'] // citrus contains ['Orange','Lemon']
slice
Nell'esempio che segue, slice
crea un nuovo array, newCar
, da myCar
. Entrambi includono un riferimento all'oggetto myHonda
. Quando il colore di myHonda
diventa viola, entrambi gli array riflettono la modifica.
// Creare newCar da myCar utilizzando slice. 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); // Mostrare i valori di myCar, newCar, e il colore di myHonda // riferiti da entrambi gli array. console.log('myCar = ' + JSON.stringify(myCar)); console.log('newCar = ' + JSON.stringify(newCar)); console.log('myCar[0].color = ' + myCar[0].color); console.log('newCar[0].color = ' + newCar[0].color); // Modificare il colore di myHonda. myHonda.color = 'purple'; console.log('The new color of my Honda is ' + myHonda.color); // Mostrare il colore di myHonda riferito da entrambi gli array. console.log('myCar[0].color = ' + myCar[0].color); console.log('newCar[0].color = ' + newCar[0].color);
Lo script scrive:
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
Il metodo slice
può essere chiamato anche per convertire gli oggetti o le collezioni Array-like in un nuovo Array. Basta legare il metodo all'oggetto. {{jsxref("Functions/arguments", "arguments")}} all'interno di una funzione è un esempio di 'array-like object'.
function list() { return Array.prototype.slice.call(arguments); } var list1 = list(1, 2, 3); // [1, 2, 3]
Il binding può essere effettuato con la funzione .call
di {{jsxref("Function.prototype")}} e può anche essere ridotto utilizzando [].slice.call(arguments)
invece di Array.prototype.slice.call
. Ad ogni modo, può essere semplificato utilizzando {{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]
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 ES2015, 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; }; } }());
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')}} |
{{Compat("javascript.builtins.Array.slice")}}