JS --splice()方法--拼接(刪除/插入)元素
Posted on 2010-06-23 10:02 幻海藍(lán)夢(mèng) 閱讀(992) 評(píng)論(1) 編輯 收藏 所屬分類(lèi): JS
原文:http://hi.baidu.com/alex_tsai/blog/item/ddd84980285aced3bc3e1ea0.html
splice() 方法用于插入、刪除或替換數(shù)組的元素。
語(yǔ)法
arrayObject.splice(index,howmany,element1,.....,elementX)
參數(shù) | 描述 |
---|---|
index |
必需。規(guī)定從何處添加/刪除元素。 |
howmany |
必需。規(guī)定應(yīng)該刪除多少元素。必須是數(shù)字,但可以是 "0"。 |
element1 | 可選。規(guī)定要添加到數(shù)組的新元素。從 index 所指的下標(biāo)處開(kāi)始插入。 |
elementX | 可選。可向數(shù)組添加若干元素。 |
返回值
如果從 arrayObject 中刪除了元素,則返回的是含有被刪除的元素的數(shù)組。
說(shuō)明
splice() 方法可刪除從 index 處開(kāi)始的零個(gè)或多個(gè)元素,并且用參數(shù)列表中聲明的一個(gè)或多個(gè)值來(lái)替換那些被刪除的元素。
提示和注釋
注釋?zhuān)?/span>請(qǐng)注意,splice() 方法與 slice() 方法的作用是不同的,splice() 方法會(huì)直接對(duì)數(shù)組進(jìn)行修改。
實(shí)例
例子 1
在本例中,我們將創(chuàng)建一個(gè)新數(shù)組,并向其添加一個(gè)元素:
輸出:
George,John,Thomas,James,Adrew,Martin
George,John,William,Thomas,James,Adrew,Martin
例子 2
在本例中我們將刪除位于 index 2 的元素,并添加一個(gè)新元素來(lái)替代被刪除的元素:
輸出:
George,John,Thomas,James,Adrew,Martin
George,John,William,James,Adrew,Martin
例子 3
在本例中我們將刪除從 index 2 ("Thomas") 開(kāi)始的三個(gè)元素,并添加一個(gè)新元素 ("William") 來(lái)替代被刪除的元素:
輸出:
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.