js數組操作方法concat()、slice()、splice()

我又專心察明智慧、狂妄和愚昧,乃知這也是捕風。因爲多有智慧就多有愁煩;加增知識的,就加增憂傷。–傳1:17,18
Then I applied myself to the understanding of wisdom, and also of madness and folly, but I learned that this,too, is a chasing after the wind. For with much wisdom comes much sorrow;the more knowledge, the more grief.

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()方法只進行刪除操作。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章