1.concat()方法
concat()方法:基于當(dāng)前數(shù)組中所有項創(chuàng)建新數(shù)組。
具體過程: 先創(chuàng)建數(shù)組的一個副本眯分,若是concat()有參數(shù)拌汇,將接收到的參數(shù)添加到副本的末尾,然后返回新構(gòu)建的數(shù)組弊决;若是沒有參數(shù)噪舀,僅僅復(fù)制當(dāng)前數(shù)組并返回副本數(shù)組。
concat()中的參數(shù)可以是一個新的數(shù)組也可以是一個字符串飘诗。
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)建一個新的數(shù)組与倡,因此當(dāng)前數(shù)組保持不變(colors數(shù)組不變)。
2.slice()
slice()方法:基于當(dāng)前數(shù)組中的一個或多個項創(chuàng)建一個新數(shù)組昆稿。
slice()方法中可以有一個或者兩個參數(shù)(代表數(shù)組的索引值纺座,0,1,2……)。接收一個參數(shù)時:返回當(dāng)前數(shù)組中從此參數(shù)位置開始到當(dāng)前數(shù)組末尾間所有項溉潭。接收兩個參數(shù)時:返回當(dāng)前數(shù)組中兩個參數(shù)位置間的所有項净响,但不返回第二個參數(shù)位置的項。
參數(shù)也可以為負(fù)數(shù)岛抄,表示從末尾算起别惦,-1代表最后一個狈茉,使用方法和正數(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ù)組的中間插入項,可以進(jìn)行刪除氯庆、插入蹭秋、替換操作。會返回一個數(shù)組堤撵,包含從原始項中刪除的項(若果沒有刪除仁讨,返回一個空數(shù)組)
刪除:兩個參數(shù),刪除起始項的位置和刪除的項數(shù)实昨。
var colors = ["red","green","blue"];
var removed = colors.splice(1,2);
alert(colors); //red
alert(removed); //green,blue
插入:在指定位置插入任意數(shù)量項洞豁,包括兩個基本參數(shù)(即刪除操作中的兩個參數(shù)類型)和要插入項的參數(shù),兩個基本參數(shù)為起始位置和0(要刪除的項數(shù)應(yīng)為0項),要插入的項參數(shù)可以是任意個(”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ù)量的項同時刪除任意數(shù)量的項刁卜,插入項數(shù)和刪除項數(shù)可以不同。參數(shù)包括兩個基本參數(shù)(即刪除操作中的兩個參數(shù)類型)和要插入項的參數(shù)曙咽。
var colors = ["red","green","blue"];
var removed = colors.splice(1,1,"purple","black");
alert(colors); //"red","purple","black","blue"
alert(removed); //"green"
其實總的理解是splice()方法包含兩個刪除項基本參數(shù)和任意個插入項參數(shù)蛔趴,兩個刪除項基本參數(shù)中第一個指定刪除位置,第二個指定刪除個數(shù)例朱,如果個數(shù)為0孝情,自然不刪除,只有指定位置功能了洒嗤。任意個插入項參數(shù)代表要插入的項值箫荡,數(shù)量不限,可省略烁竭,省略時splice()方法只進(jìn)行刪除操作菲茬。