concat()方法
concat()方法:基于當前數組中所有項創建新數組。
具體過程為:先創建數組的一個副本,若是concat()存在參數,將接收到的參數添加到副本的末尾,然后返回新構建的數組;若是沒有傳遞參數,僅僅復制當前數組并返回副本數組。
concat()中的參數可以是一個新的數組也可以是一個字符串。
var colors = ["red","green","blue"]; var colors2 = colors.concat("yellow",["black","brown"]); alert(colors); alert(colors2);
結果為colors為數組[“red”,”green”,”blue”];
colors2為數組[“red”,”green”,”blue”,”yellow”,”black”,”brown”];
concat()方法只是用當前數組重新創建一個新的數組,因此當前數組保持不變(colors數組不變)。
slice()方法
slice()方法:基于當前數組中的一個或多個項創建一個新數組。
slice()方法中可以有一個或者兩個參數(代表數組的索引值,0,1,2……)。接收一個參數時:返回當前數組中從此參數位置開始到當前數組末尾間所有項。接收兩個參數時:返回當前數組中兩個參數位置間的所有項,但不返回第二個參數位置的項。
參數也可以為負數,表示從末尾算起,-1代表最后一個,使用方法和正數一樣。
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);
結果為:[“blue”, “yellow”, “black”, “brown”]
[“green”, “blue”, “yellow”]
[“blue”, “yellow”]
[“yellow”, “black”]
另外slice()方法還可用于對數組的移除
Array.prototype.remove = function(from, to) { var rest = this.slice((to || from) + 1 || this.length); this.length = from <0 ? this.length + from : from; return this.push.apply(this, rest); };
對于
rest = this.slice((to || from) + 1 || this.length);
若to不等于0,(to||from)就等于to,且to+1不等于0,則((to || from) + 1 || this.length)為to+1),若to+1=0,((to || from) + 1 || this.length)為this.length;
若to=0,(to||from)取from,若from+1不等于0,((to || from) + 1 || this.length)為from+1,若from+1=0, ((to || from) + 1 || this.length)為this.length。
splice()方法
splice()主要用途是向當前數組的中間插入項,可以進行刪除、插入、替換操作。會返回一個數組,包含從原始項中刪除的項(若果沒有刪除,返回一個空數組)
刪除:兩個參數,刪除起始項的位置和刪除的項數。
var colors = ["red","green","blue"]; var removed = colors.splice(1,2); alert(colors); //red alert(removed); //green,blue
插入:在指定位置插入任意數量項,包括兩個基本參數(即刪除操作中的兩個參數類型)和要插入項的參數,兩個基本參數為起始位置和0(要刪除的項數應為0項),要插入的項參數可以是任意個(”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); //空數組
替換:向指定位置插入任意數量的項同時刪除任意數量的項,插入項數和刪除項數可以不同。參數包括兩個基本參數(即刪除操作中的兩個參數類型)和要插入項的參數。
var colors = ["red","green","blue"]; var removed = colors.splice(1,1,"purple","black"); alert(colors); //"red","purple","black","blue" alert(removed); //"green"
其實總的理解是splice()方法包含兩個刪除項基本參數和任意個插入項參數,兩個刪除項基本參數中第一個指定刪除位置,第二個指定刪除個數,如果個數為0,自然不刪除,只有指定位置功能了。任意個插入項參數代表要插入的項值,數量不限,可省略,省略時splice()方法只進行刪除操作。
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com