Array.prototype.slice()
Baseline
Widely available
This feature is well established and works across many devices and browser versions. Itâs been available across browsers since 2015å¹´7æ.
slice() æ¹æ³æåå³ä¸åæ°é£åç©ä»¶ï¼çºåé£åé¸æä¹ begin è³ endï¼ä¸å« endï¼é¨åçæ·ºæ·è²ï¼shallow copyï¼ãè忬çé£åå°ä¸æè¢«ä¿®æ¹ã
å試ä¸ä¸
const animals = ["ant", "bison", "camel", "duck", "elephant"];
console.log(animals.slice(2));
// Expected output: Array ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4));
// Expected output: Array ["camel", "duck"]
console.log(animals.slice(1, 5));
// Expected output: Array ["bison", "camel", "duck", "elephant"]
console.log(animals.slice(-2));
// Expected output: Array ["duck", "elephant"]
console.log(animals.slice(2, -1));
// Expected output: Array ["camel", "duck"]
console.log(animals.slice());
// Expected output: Array ["ant", "bison", "camel", "duck", "elephant"]
èªæ³
arr.slice([begin[, end]])
忏
begin鏿æ§-
èªåªä¸åç´¢å¼ï¼èµ·å§çº 0ï¼éå§æåæ·è²ãå¯ä½¿ç¨è² æ¸ç´¢å¼ï¼è¡¨ç¤ºç±é£åçææ«é éå§æåã
slice(-2)代表æ·è²é£åä¸çæå¾å ©åå ç´ ãåå¦beginçº undefinedï¼åsliceæå¾ç´¢å¼0éå§æåã end鏿æ§-
è³åªä¸åç´¢å¼ï¼èµ·å§çº 0ï¼ä¹å忢æåã
sliceæåä½ä¸å å«è³ç´¢å¼endãèä¾ä¾èªªï¼slice(1,4)æåäºé£åä¸ç¬¬äºåå ç´ è³ç¬¬ååå ç´ åçºæ¢ï¼å ç´ ç´¢å¼ 1ã2 以å 3ï¼ä¾æ·è²ãå¯ä½¿ç¨è² æ¸ç´¢å¼ï¼è¡¨ç¤ºç±é£åçææ«é éå§æåãslice(2,-1)代表æ·è²é£åä¸ç¬¬ä¸åå ç´ è³åæ¸ç¬¬äºåå ç´ ãè¥çç¥äºendï¼åsliceææåè³é£åçæå¾ä¸åå ç´ ï¼arr.lengthï¼ãåå¦end大æ¼é£åçé·åº¦ï¼sliceææåè³é£åçæå¾ä¸åå ç´ ï¼arr.lengthï¼ã
åå³å¼
ä¸åå 嫿åä¹å ç´ çæ°é£åã
說æ
slice ä¸æä¿®æ¹åæ¬çé£åï¼èæ¯åå³ç±åæ¬çé£å淺層è¤è£½çå
ç´ ãåå§é£åçå
ç´ ææç
§ä¸åè¦åæ·è²ï¼
- å¦æè©²å
ç´ æ¯åå°è±¡å¼ç¨ï¼ä¸æ¯å¯¦éçå°è±¡ï¼ï¼
sliceææ·è²éåå°è±¡å¼ç¨å°æ°çé£åå §ãå ©åå°è±¡å¼ç¨é½å¼ç¨äºåä¸åå°è±¡ãå¦æè¢«å¼ç¨çå°è±¡ç¼çæ¹è®ï¼åæ°çååä¾çé£åä¸çéåå ç´ ä¹æç¼çæ¹è®ã - å°æ¼åä¸²ãæ¸åã叿ä¾èªª (䏿¯
StringãNumberæèBooleanå°è±¡),sliceææ·è²éäºå¼å°æ°çé£åå §ãå¨å¥çé£åå §ä¿®æ¹éäºåä¸²ãæ¸åææ¯å¸æï¼å°ä¸æå½±é¿å¦ä¸åé£åã
å¦ææ·»å äºæ°çå ç´ å°å¦ä¸åé£åå §ï¼åå¦ä¸å䏿åå°å½±é¿ã
ç¯ä¾
>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 = " + 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);
// 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ï¼ç©ä»¶
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 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 Function.prototype and it can also be reduced using [].slice.call(arguments) instead of Array.prototype.slice.call. Anyway, it can be simplified using 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 null/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 |
|---|
| ECMAScript® 2027 Language Specification> # sec-array.prototype.slice> |