js陣列常用方法總結
阿新 • • 發佈:2020-08-11
數 組 常 見 操 作 總 結
陣列是 js 中常見的資料格式,也是面試的一個常見考點,作為一個前端工程師,我們需要熟練的掌握有關陣列的操作技巧。下面我們就開始陣列的常用方法的總結吧。
數 組 去 重
陣列去重是面試的時候一道常見的面試題,同樣的在工作中也會經常性遇到的一個問題,在 ES6 語法中有個非常快速且簡單的方法,使用 new Set()以及 Array.from()或者展開運算子(...)來進行陣列去重。
let array = [1, 2, 3, 4, 5, 7, 8, 1, 2, 3] // 方法一 var uniquArray = Array.from(new Set(array)); console.log(uniquArray); // returns [1, 2, 3, 4, 5, 7, 8] // 方法二 var uniquArray2 = […new Set(array)]; console.log(uniquArray2); // returns [1, 2, 3, 4, 5, 7, 8]
數 組 元 素 的 都 替 換
日常開發中經常需要替換或者刪除一些指定的資料,遇到這種場景時一定要聯想到 Array.protoType.splice 這個方法。這個方法傳參的時候引數有點多。第一個引數是開始的索引,第二個引數是需要刪除的數量,剩下的就是需要新增的值(可以是一個或者多個)。【splice 方法會改變原陣列,返回原陣列被替換或者刪除的項組成的陣列】
let numArray = [1,2,3,4,5,6,7,8,9]; // 元素的替換 let sp = numArray.splice(0, 2, 'A'.'B'); console.log(numArray); // returns ['A', 'B', 3, 4, 5, 6, 7, 8, 9] console.log(sp); // returns [1,2] // 刪除元素 let sp = numArray.splice(0, 2); console.log(numArray); // returns [3, 4, 5, 6, 7, 8, 9] console.log(sp); // returns [1,2]
數 組 的 遍 歷
常見的陣列遍歷有:for 迴圈,foreach 迴圈,forof 遍歷。。。。。本次主要說一些 ES6 的新的方法或者不太常用的。
map 迴圈
有返回值,可以 return 出來。不影響原來的陣列,會生成一個行的陣列
let array = [1,2,3]
let result = array.map((item,index,array)=>{
return item*item
})
conslole.log(result) // returns [1,4 ,9]
console.log(array) // returns [1,2.3]
filter 遍歷
不會改變原始陣列,返回新陣列
let arr = [
{ id: 1, text: 'aa', done: true },
{ id: 2, text: 'bb', done: false }
]
let result = arr.filter((item) => item.done)
console.log(result) // returns [ { id: 1, text: 'aa', done: true } ]
console.log(arr) // returns [{ id: 1, text: 'aa', done: true },{ id: 2, text: 'bb', done: false }]
every 遍歷
對陣列中的每一項執行給定函式,如果該函式對每一項返回 true,則返回 true。不改變原陣列
let arr = [1, 2, 3, 4, 5, 6];
let result = arr.every((item) => {
return item > 3
})
console.log(result) // returns false
console.log(arr) // [1,2,3,4,5,6]
some 遍歷
對陣列中的每一項執行給定函式,如果有一項返回 true,則返回 true。不改變原陣列
let arr = [1, 2, 3, 4, 5, 6];
let result = arr.every((item) => {
return item > 3
})
console.log(result) // returns true
console.log(arr) // [1,2,3,4,5,6]
Array.from
不改變元素組
var friends = [
{ name: 'John', age: 22 },
{ name: 'Peter', age: 23 },
{ name: 'Mark', age: 24 },
{ name: 'Maria', age: 22 },
{ name: 'Monica', age: 21 },
{ name: 'Martha', age: 19 }
]
var friendsNames = Array.from(friends, ({ name }) => name);
console.log(friendsNames); // returns [“John”, “Peter”, “Mark”, “Maria”, “Monica”, “Martha”]
陣列轉換成物件
除了使用 map()的類似的迭代方法能達到目的外,如果你正好希望物件的 key 就是陣列的索引,那麼還有一個超級快速的方法。
let arr = ['a', 'b', 'c', 'd'];
let result = { ...arr };
console.log(result); // returns { '0': 'a', '1': 'b', '2': 'c', '3': 'd' }
陣列的填充
使用制定的元素填充陣列,其實就是用預設內容初始化陣列。該函式有三個引數。value:填充值。start:填充起始位置,可以省略。end:填充結束位置,可以省略,實際結束位置是 end-1。【修改原陣列】
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
arr.fill(7, 2, 5)
console.log(arr) // returns [1,2,7,7,7,6,7,8,9,10,11]