slice
- 基于當(dāng)前數(shù)組中的一或多個項(xiàng)創(chuàng)建一個新數(shù)組
- 可以接受一或兩個參數(shù)苛预,即要返回項(xiàng)的起始和結(jié)束位置,但不包括結(jié)束位置
- 在只有一個參數(shù)的情況下,返回從該參數(shù)指定位置開始到當(dāng)前數(shù)組末尾的所有項(xiàng)
- 不會影響原始數(shù)組
var colors = ["red", "green", "blue", "yellow", "purple"];
var colors2 = colors.slice(1);
var colors3 = colors.slice(1,4);
console.log(colors); // ["red", "green", "blue", "yellow", "purple"]
console.log(colors2); // ["green","blue","yellow","purple"]
console.log(colors3); // ["green","blue","yellow"]
如果參數(shù)中有一個負(fù)數(shù)热某,則用數(shù)組長度加上該數(shù)來確定相應(yīng)的位置胳螟。例如筹吐,在一個包含5項(xiàng)的數(shù)組上調(diào)用
slice(-2,-1)
與調(diào)用slice(3,4)
得到的結(jié)果相同。如果結(jié)束位置小于起始位置丘薛,則返回空數(shù)組。
splice
- 主要用途是向數(shù)組的中部插入元素
- 會影響原始數(shù)組
刪除
要實(shí)現(xiàn) splice
的刪除功能舍扰,最多只能傳兩個參數(shù)
一個參數(shù)
刪除從參數(shù)位置到當(dāng)前數(shù)組末尾的所有項(xiàng)
var colors = ["red", "green", "blue", "black"];
var spliceColors = colors.splice(0)
console.log(colors) // []
console.log(spliceColors) // ["red", "green", "blue", "black"]
兩個參數(shù)
起始位置和要刪除元素的數(shù)量
var colors = ["red", "green", "blue", "black"];
var spliceColors = colors.splice(0,2)
console.log(colors) // ["blue", "black"]
console.log(spliceColors) // ["red", "green"]
插入
要實(shí)現(xiàn) splice
的插入功能希坚,至少傳3個參數(shù):起始位置、0(要刪除元素的數(shù)量)和要插入的元素裁僧。如果要插入多個元素,可以再傳入第四锅知、第五,以至任意多個元素
var colors = ["red", "green", "blue", "black"];
var spliceColors = colors.splice(1,0,'yellow','white')
console.log(colors) // ["red", "yellow", "white", "green", "blue", "black"]
console.log(spliceColors) // []
替換
splice
可以向指定位置插入任意數(shù)量的項(xiàng)售睹,且同時刪除任意數(shù)量的項(xiàng)。要實(shí)現(xiàn) splice
的替換功能昌妹,只需指定3個參數(shù):起始位置、要刪除元素的數(shù)量和要插入的元素飞崖。插入的項(xiàng)數(shù)不必與刪除的項(xiàng)數(shù)相等
var colors = ["red", "green", "blue", "black"];
var spliceColors = colors.splice(1,2,'yellow','white')
console.log(colors) // ["red", "yellow", "white", "black"]
console.log(spliceColors) // ["green", "blue"]