Array methods

Add/remove items

  • arr.push(...items) – adds items to the end,

  • arr.pop() – extracts an item from the end,

  • arr.shift() – extracts an item from the beginning,

  • arr.unshift(...items) – adds items to the beginning.

splice 插入、移除、替換 array 的值

// array 可以使用 delete 刪除值,但屬性仍然存在
let arr = ["I", "go", "home"];
delete arr[1]; // remove "go"
alert( arr[1] ); // undefined
// now arr = ["I",  , "home"];
alert( arr.length ); // 3

// splice
arr.splice(index[, deleteCount, elem1, ..., elemN])

// delete
let arr = ["I", "study", "JavaScript"];
arr.splice(1, 1); // from index 1 remove 1 element
alert( arr ); // ["I", "JavaScript"]

// replace
let arr = ["I", "study", "JavaScript", "right", "now"];
// remove 3 first elements and replace them with another
arr.splice(0, 3, "Let's", "dance");
alert( arr ) // now ["Let's", "dance", "right", "now"]

// splice 返回移除的值
let arr = ["I", "study", "JavaScript", "right", "now"];
// remove 2 first elements
let removed = arr.splice(0, 2);
alert( removed ); // "I", "study" <-- array of removed elements

// insert
let arr = ["I", "study", "JavaScript"];
// from index 2
// delete 0
// then insert "complex" and "language"
arr.splice(2, 0, "complex", "language");
alert( arr ); // "I", "study", "complex", "language", "JavaScript"

// 可以用負數 index
let arr = [1, 2, 5];
// from index -1 (one step from the end)
// delete 0 elements,
// then insert 3 and 4
arr.splice(-1, 0, 3, 4);
alert( arr ); // 1,2,3,4,5

slice 返回複製指定位置新的 array

concat 串聯 array 或值

Iterate: forEach

arr.forEach(func()) 將 array 中所有元素帶入函式內。

Searching in array

indexOf/lastIndexOf and includes

  • arr.indexOf(item, from) looks for item starting from index from, and returns the index where it was found, otherwise -1.

  • arr.lastIndexOf(item, from) – same, but looks for from right to left.

  • arr.includes(item, from) – looks for item starting from index from, returns true if found.

find and findIndex 若 array 的元素是物件,要找到特定物件用 find,只返回第一個符合函示元素。

  • item is the element.

  • index is its index.

  • array is the array itself.

filter 跟 find 很像,但會返回所有符合函式的元素。

Transform an array

map 將 array 每個元素帶入函式並返回新的 array

sort(fn)

reverse

split and join 將 string 用符號分開成 array / 將 array 用符號連接成 string

reduce/reduceRight

  • previousValue – is the result of the previous function call, initial for the first call.

  • item – is the current array item.

  • index – is its position.

  • array – is the array.

sum

current

result

the first call

0

1

1

the second call

1

2

3

the third call

3

3

6

the fourth call

6

4

10

the fifth call

10

5

15

Array.isArray

Most methods support “thisArg”

Last updated

Was this helpful?