JavaScript 常用陣列方法

concat()

concat() 將陣列進行串接,會回傳一個新的陣列。

const a = [1, 2, 3];
a.concat(4, 5); // [1, 2, 3, 4, 5]
a.concat([8, 9]); // [1, 2, 3, 8, 9]
a.concat([4, 5], [6, 7]); // [1, 2, 3, 4, 5, 6, 7]

forEach()

forEach() 方法會通過迭代陣列元素,針對陣列中的每個元素執行指定的動作。 callback 函數會傳入三個參數:(element, index, array) 分別代表陣列目前元素、陣列索引、目前陣列

const data = [1, 2, 3, 4, 5];
let sum = 0;
data.forEach(value => sum += value);
console.log(sum); // 15
// use callback function
const arr = [1, 2, 3, 4, 5];
arr.forEach((element, index, arr) =>
console.log(index + ' => ' + element)
);

filter()

filter() 方法透過迭代陣列元素並透過給定的條件來過濾元素,並回傳一個新的陣列。與 forEach 一樣,callback function 內可以傳入三個參數。

const arr = [1, 2, 3, 4, 5];
const res = arr.filter(
(elm, index, arr) => elm > 3
);
console.log(res); // [4, 5]

map()

map() 方法會把調用他的陣列元素逐一傳給你指定的函式,並回傳一個新的陣列。

const a = [1, 2, 3];
const b = a.map( s => s + 1);
console.log(b); // b = [2, 3, 4]

push() 和 pop()

push() 方法把你的陣列當作堆疊,push() 會在你陣列最尾端附加一個或多個元素,並回傳陣列新的長度。 pop() 方法和 push() 剛好相反,他是刪除陣列最後一個元素,並回傳移除的值。

const stack = [];
stack.push(1, 2, 3); // [1, 2, 3]
stack.push([4, 5, 6]); // [1, 2, 3, [4, 5, 6]]
stack.pop(); // [4, 5, 6]

reverse()

reverse 方法會將陣列中的元素順序反轉,並回傳反轉後新的陣列

const a = ['foo', 'Bar'];
console.log(a.reverse()) // ['Bar', 'foo']

reduce()

reduce 可以處理陣列內的元素,並依序執行 callback。

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce(
(total, num) => total + num, 0 // 後面的 0 是給定一個預設值,代表 total = 0。
);
console.log(sum); // 15

shift()

shift() 方法是將陣列的第一個元素移除,並返回被刪除的元素。

const arr = ['a', 'b', 'c', 'd'];
arr; // [a, b, c, d]
const shiftArr = arr.shift();
console.log(arr); // [b, c, d]
console.log(shiftArr); // a

sort()

sort() 將原本陣列上的元素排序並回傳排序後的陣列。

const a = ['peng', 'jie', 'Taichung', 9];
console.log(a.sort()); // [9, 'Taichung', 'jie', 'peng']

slice()

可以把陣列切片,回傳指定的部分,他的引數分別指定回傳的切片開頭結尾slice(start, end)

const a = [1, 2, 3, 4, 5];
a.slice(0, 4); // [1, 2, 3, 4]
a.slice(-1); // [5], 代表最後陣列最後一個元素。

splice()

splice() 方法是用來插入或移除陣列元素的通用方法。

splice(index, delete, item)

  • index 代表新增/刪除的元素位置。
  • delete 需要刪除的元素數量,設定為 0 不會刪除任何元素。
  • item 需要新增到陣列的元素。
const arr = ['pengjie', 'taichung', 'taiwan'];
arr.splice(2, 0, 'CYUT'); // 新增; ['pengjie', 'taichung', 'CYUT', 'taiwan']
arr.splice(1, 1); // 刪除; ['pengjie', 'CYUT', 'taiwan']

toString()

const a = ['a', 'b', 'c', 1, 2, 3];
a; // ['a', 'b', 'c', 1, 2, 3]
a.toString(); // 'a,b,c,1,2,3'

indexOf() 和 lastIndexOf()

indexOf() 方法是回傳陣列中第一個和值相符的元素索引。 lastIndexOf() 方法是回傳陣列中最後一個和值相符的元素索引。 如果都在陣列都找不到元素,返回索引值為 -1

const a = ['taiwan', 'taichung', 'taipei', 'taichung', 'taiwan', 'taipei'];
a.indexOf('taichung'); // a[1]
a.lastIndexOf('taichung'); // a[3]
a.indexOf('Miaoli'); // -1

join()

方法將陣列的所有元素轉成字串並且串接起來,再回傳。也可以另外指定一個額外的字元符號來分隔字串中的元素,如果沒有指定,預設使用逗號:

const a = ['foo', 'Bar'];
a.join(); // 'foo,Bar'
a.join(' '); // 'foo Bar'
a.join(''); // 'fooBar'
a.join('-'); // 'foo-Bar'

Reference