原文:http://hi.baidu.com/alex_tsai/blog/item/ddd84980285aced3bc3e1ea0.html
splice() 方法用于插入、刪除或替換數組的元素。
語法
arrayObject.splice(index,howmany,element1,.....,elementX)
參數 | 描述 |
---|---|
index |
必需。規定從何處添加/刪除元素。 |
howmany |
必需。規定應該刪除多少元素。必須是數字,但可以是 "0"。 |
element1 | 可選。規定要添加到數組的新元素。從 index 所指的下標處開始插入。 |
elementX | 可選。可向數組添加若干元素。 |
返回值
如果從 arrayObject 中刪除了元素,則返回的是含有被刪除的元素的數組。
說明
splice() 方法可刪除從 index 處開始的零個或多個元素,并且用參數列表中聲明的一個或多個值來替換那些被刪除的元素。
提示和注釋
注釋:請注意,splice() 方法與 slice() 方法的作用是不同的,splice() 方法會直接對數組進行修改。
實例
例子 1
在本例中,我們將創建一個新數組,并向其添加一個元素:
輸出:
George,John,Thomas,James,Adrew,Martin
George,John,William,Thomas,James,Adrew,Martin
例子 2
在本例中我們將刪除位于 index 2 的元素,并添加一個新元素來替代被刪除的元素:
輸出:
George,John,Thomas,James,Adrew,Martin
George,John,William,James,Adrew,Martin
例子 3
在本例中我們將刪除從 index 2 ("Thomas") 開始的三個元素,并添加一個新元素 ("William") 來替代被刪除的元素:
輸出:
George,John,Thomas,James,Adrew,Martin
George,John,William,Martin
?1) JS- ARRAY--方法解釋。
? concat ? Joins ? two ? arrays ? and ? returns ? a ? new ? array. ? ? ?
? join ? Joins ? all ? elements ? of ? an ? array ? into ? a ? string. ? ?
? pop ? Removes ? the ? last ? element ? from ? an ? array ? and ? returns ? that ? element. ? ?
? push ? Adds ? one ? or ? more ? elements ? to ? the ? end ? of ? an ? array ? and ? returns ? that ? last ? element ? added. ? ?
? reverse ? Transposes ? the ? elements ? of ? an ? array: ? the ? first ? array ? element ? becomes ? the ? last ? and ? the ? last ? becomes ? the ? first. ? ?
? shift ? Removes ? the ? first ? element ? from ? an ? array ? and ? returns ? that ? element ? ?
? slice ? Extracts ? a ? section ? of ? an ? array ? and ? returns ? a ? new ? array. ? ?
? splice ? Adds ? and/or ? removes ? elements ? from ? an ? array. ? ?
? sort ? Sorts ? the ? elements ? of ? an ? array. ? ?
? toString ? Returns ? a ? string ? representing ? the ? specified ? object. ? ?
? unshift ? Adds ? one ? or ? more ? elements ? to ? the ? front ? of ? an ? array ? and ? returns ? the ? new ? length ? of ? the ? array.