Get to know MDN better
此頁面由社群從英文翻譯而來。了解更多並加入 MDN Web Docs 社群。
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)。而原本的陣列將不會被修改。
自哪一個索引(起始為 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 不會修改原本的陣列,而是回傳由原本的陣列淺層複製的元素。原始陣列的元素會按照下列規則拷貝:
如果添加了新的元素到另一個陣列內,則另一個不會受到影響。
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.
This script writes:
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'.
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.
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.)
| ECMAScript® 2027 Language Specification # sec-array.prototype.slice |
Enable JavaScript to view this browser compatibility table.
This page was last modified on 2025年7月14日 by MDN contributors.
Your blueprint for a better internet.
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998–2026 by individual mozilla.org contributors. Content available under a Creative Commons license.