1.concat()方法
concat()方法:基于當(dāng)前數(shù)組中所有項(xiàng)創(chuàng)建新數(shù)組。
具體過(guò)程: 先創(chuàng)建數(shù)組的一個(gè)副本,若是concat()有參數(shù),將接收到的參數(shù)添加到副本的末尾,然后返回新構(gòu)建的數(shù)組;若是沒(méi)有參數(shù),僅僅復(fù)制當(dāng)前數(shù)組并返回副本數(shù)組。
concat()中的參數(shù)可以是一個(gè)新的數(shù)組也可以是一個(gè)字符串。
var colors = ["red","green","blue"];
var colors2 = colors.concat("yellow",["black","brown"]);
alert(colors);
alert(colors2);
結(jié)果為colors為數(shù)組[“red”,”green”,”blue”];
colors2為數(shù)組[“red”,”green”,”blue”,”yellow”,”black”,”brown”];
concat()方法只是用當(dāng)前數(shù)組重新創(chuàng)建一個(gè)新的數(shù)組,因此當(dāng)前數(shù)組保持不變(colors數(shù)組不變)。
2.slice()
slice()方法:基于當(dāng)前數(shù)組中的一個(gè)或多個(gè)項(xiàng)創(chuàng)建一個(gè)新數(shù)組。
slice()方法中可以有一個(gè)或者兩個(gè)參數(shù)(代表數(shù)組的索引值,0,1,2……)。接收一個(gè)參數(shù)時(shí):返回當(dāng)前數(shù)組中從此參數(shù)位置開始到當(dāng)前數(shù)組末尾間所有項(xiàng)。接收兩個(gè)參數(shù)時(shí):返回當(dāng)前數(shù)組中兩個(gè)參數(shù)位置間的所有項(xiàng),但不返回第二個(gè)參數(shù)位置的項(xiàng)。
參數(shù)也可以為負(fù)數(shù),表示從末尾算起,-1代表最后一個(gè),使用方法和正數(shù)一樣。
var colors = ["red","green","blue","yellow","black","brown"];
var colors2 = colors.slice(2);
var colors3 = colors.slice(1,4);
var colors4 = colors.slice(2,-2);
var colors5 = colors.slice(-3,-1);
console.log(colors2);
console.log(colors3);
console.log(colors4);
console.log(colors5);
結(jié)果為:
[“blue”, “yellow”, “black”, “brown”]
[“green”, “blue”, “yellow”]
[“blue”, “yellow”]
[“yellow”, “black”]
3.splice()
splice()主要用途是向當(dāng)前數(shù)組的中間插入項(xiàng),可以進(jìn)行刪除、插入、替換操作。會(huì)返回一個(gè)數(shù)組,包含從原始項(xiàng)中刪除的項(xiàng)(若果沒(méi)有刪除,返回一個(gè)空數(shù)組)
刪除:兩個(gè)參數(shù),刪除起始項(xiàng)的位置和刪除的項(xiàng)數(shù)。
var colors = ["red","green","blue"];
var removed = colors.splice(1,2);
alert(colors); //red
alert(removed); //green,blue
插入:在指定位置插入任意數(shù)量項(xiàng),包括兩個(gè)基本參數(shù)(即刪除操作中的兩個(gè)參數(shù)類型)和要插入項(xiàng)的參數(shù),兩個(gè)基本參數(shù)為起始位置和0(要?jiǎng)h除的項(xiàng)數(shù)應(yīng)為0項(xiàng)),要插入的項(xiàng)參數(shù)可以是任意個(gè)(”red”,”green”,”blue”)。
var colors = ["red","green","blue"];
var removed = colors.splice(1,0,"yellow","orange");
alert(colors); //"red","yellow","orange","green","blue"
alert(removed); //空數(shù)組
替換:向指定位置插入任意數(shù)量的項(xiàng)同時(shí)刪除任意數(shù)量的項(xiàng),插入項(xiàng)數(shù)和刪除項(xiàng)數(shù)可以不同。參數(shù)包括兩個(gè)基本參數(shù)(即刪除操作中的兩個(gè)參數(shù)類型)和要插入項(xiàng)的參數(shù)。
var colors = ["red","green","blue"];
var removed = colors.splice(1,1,"purple","black");
alert(colors); //"red","purple","black","blue"
alert(removed); //"green"
其實(shí)總的理解是splice()方法包含兩個(gè)刪除項(xiàng)基本參數(shù)和任意個(gè)插入項(xiàng)參數(shù),兩個(gè)刪除項(xiàng)基本參數(shù)中第一個(gè)指定刪除位置,第二個(gè)指定刪除個(gè)數(shù),如果個(gè)數(shù)為0,自然不刪除,只有指定位置功能了。任意個(gè)插入項(xiàng)參數(shù)代表要插入的項(xiàng)值,數(shù)量不限,可省略,省略時(shí)splice()方法只進(jìn)行刪除操作。