DAY 24
0
Modern Web

陣列-一些操作陣列好用的方法 (二)

unshift

unshift 會添加一個或多個元素至陣列的開頭，並回傳陣列的新長度

``````Array.unshift(要新增的資料)
``````

``````var a=[1,2,3]
console.log(a.unshift(4,5)); // 5
console.log(a); // [4,5,1,2,3]
``````

reverse()

reverse 會將原陣列反轉，並且回傳原陣列

``````Array.reverse()
``````

``````var a=['one','two','three'];
var reversed=a.reverse();
console.log(a);  // ['three','two','one']
console.log(reversed); // ['three','two','one']
``````

reverse 會將原陣列反轉，並且回傳原陣列的位置

``````var a=['one','two','three'];
var reversed=a.reverse();
console.log(a);  // ['three','two','one']
console.log(reversed); // ['three','two','one']

reversed.push('four');

console.log(a); // ['three','two','one','four']
console.log(reversed); //['three','two','one','four']
``````

splice()

splice 包含三個參數

1. start：移除或要添加的序列號碼
2. deleteCount：要移除的長度
3. item：要加入的元素
``````Array.splice(start,deleteCount,item)
``````

``````var a=[1,2,3,4,5,6,7,8];
a.splice(5,1);  //
console.log(a); // [1,2,3,4,5,6,7,8]
``````

``````var a=[1,2,3,4,5,6,7,8];
a.splice(5,1,100);
console.log(a); // [1,2,3,4,5,100,7,8] ( 6 被移除，100 被加到第 5 個位置)
``````
``````var b=[1,2,3,4,5,6,7,8];
b.splice(5,3,100,300,500);
console.log(b); // [1,2,3,4,5,100,300,500] (6,7,8被移除，100,300,500被加進index為5,6,7位置)
``````
``````var c=[1,2,3,4,5,6,7,8];
c.splice(5,0,300);
console.log(c); // [1,2,3,4,5,300,6,7,8] (沒有元素被移除，100被加進index為5的位置)
``````