JS Array的各種常見操作分類- 來掃一遍mdn array fn吧


由於 wordpress 對於撰寫code 的編輯方式越來越難用了,後續會轉移到 medium為主,歡迎前往閱讀~
=> 前往Medium好讀版


Js 的 Array 有很多好用的function,這次複習著重在每個fn的 input , output ,期許增加熟悉度,能使用得更上手!

開始囉~


1.刪減新增元素

arr.filter

let modifiedArray = arr.filter(callback(currentValue[, index[, array]]) {
// return element for newArray, if true
}[, thisArg]);

arr.slice

let modifiedArray = arr.slice([start[, end]])

特性:shallow copy only,測試如下:https://sasacode.wordpress.com/media/a1acc397be19fbe00166725132d5b41a

arr.splice

let modifiedArray = array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

arr.shift

arr.unshift

arr.pop

arr.push

詳細可參考 JS 20 ways to control Array


2. 遍歷元素

arr.map

let newArray = arr.map(callback(currentValue[, index[, array]]) {
// return every element for newArray, after executing something
}[, thisArg]);

arr.forEach

arr.reduce

let anything = arr.reduce(callback( accumulator, currentValue, [, index[, array]] ){
// return anything you want
}[, initialAccumulatorValue])

arr.reduceRight


3.查找元素

arr.find
arr.findIndex
arr.indexOf
arr.lastIndexOf
arr.includes

let boolean = arr.includes(valueToFind[, fromIndex])

4. 檢驗元素

arr.every
arr.some

5. initiate Array , combined Array

arr.fill

arr.concat


5. 類型轉換

array -> obj

let newObj = Object.fromEntries(iterable);

Some built-in types, such as Array or Map, have a default iteration behavior, while other types (such as Object) do not.

obj -> array

let newArray = array.entries(obj)

array->string

let newStr = arr.join([separator])
let newStr = arr.toString()

string -> array

let newArray = Array.from(arrayLike [, mapFn [, thisArg]])

延伸:What is arrayLike ? What’s different with Array?
 Array-like objects do not have any of Array’s functions, and for-in loops don’t even work!
see reference

let newArray = str.split([separator[, limit]])

進階使用技巧參考:上手使用 JavaScript 的 Map、Reduce 吧!