slice
- 基于當(dāng)前數(shù)組中的一或多個(gè)項(xiàng)創(chuàng)建一個(gè)新數(shù)組
- 可以接受一或兩個(gè)參數(shù),即要返回項(xiàng)的起始和結(jié)束位置,但不包括結(jié)束位置
- 在只有一個(gè)參數(shù)的情況下,返回從該參數(shù)指定位置開始到當(dāng)前數(shù)組末尾的所有項(xiàng)
- 不會(huì)影響原始數(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ù)中有一個(gè)負(fù)數(shù),則用數(shù)組長度加上該數(shù)來確定相應(yīng)的位置。例如,在一個(gè)包含5項(xiàng)的數(shù)組上調(diào)用
slice(-2,-1)與調(diào)用slice(3,4)得到的結(jié)果相同。如果結(jié)束位置小于起始位置,則返回空數(shù)組。
splice
- 主要用途是向數(shù)組的中部插入元素
- 會(huì)影響原始數(shù)組
刪除
要實(shí)現(xiàn) splice 的刪除功能,最多只能傳兩個(gè)參數(shù)
一個(gè)參數(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"]
兩個(gè)參數(shù)
起始位置和要?jiǎng)h除元素的數(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個(gè)參數(shù):起始位置、0(要?jiǎng)h除元素的數(shù)量)和要插入的元素。如果要插入多個(gè)元素,可以再傳入第四、第五,以至任意多個(gè)元素
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í)刪除任意數(shù)量的項(xiàng)。要實(shí)現(xiàn) splice 的替換功能,只需指定3個(gè)參數(shù):起始位置、要?jiǎng)h除元素的數(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"]