1、String.slice(start,end)
returns a string containing a slice, or substring, of string. It does not modify string。
slice()返回一個子片段,對原先的string沒有影響,與subString的區別是,還可以用負數當參數,相當於是length+start,length+end.
Example:
var s = "abcdefg"; s.slice(0,4) // Returns "abcd" s.slice(2,4) // Returns "cd" s.slice(4) // Returns "efg" s.slice(3,-1) // Returns "def" s.slice(3,-2) // Returns "de" s.slice(-3,-1) // Should return "ef"; returns "abcdef" in IE 4
2.Array.slice(start,end)
returns a slice, or subarray, of array. The returned array contains the element specified by start and all subsequent elements up to, but not including, the element specified by end. If end is not specified, the returned array contains all elements from the start to the end of array.
返回從start開始到end的子數組,如果end這個參數沒有被設置,則返回從start開始到最后的數組元素。
Example:
var a = [1,2,3,4,5]; a.slice(0,3); // Returns [1,2,3] a.slice(3); // Returns [4,5] a.slice(1,-1); // Returns [2,3,4] a.slice(-3,-2); // Returns [3]; buggy in IE 4: returns [1,2,3]
除了正常用法,slice 經常用來將 array-like 對象轉換為 true array。在一些框架中會經常有這種用法。
Array.prototype.slice.call(arguments);//將參數轉換成真正的數組.
因為arguments不是真正的Array,雖然arguments有length屬性,但是沒有slice方法,所以呢,Array.prototype.slice()執行的時候,Array.prototype已經被call改成arguments了,因為滿足slice執行的條件(有length屬性).