
前言
我們在日常開發中,與接口打交道最多了,前端通過通路後端接口,然後将接口資料二次處理渲染到頁面當中。
二次處理的過程是 考驗
Coder
對
Array
是否熟練 以及 在 何種 場景下使用哪種方法處理最優 。
小編,在最近開發中就遇到了
Array
問題, 在處理複雜的業務需求時,沒想到
Array
有類似的方法,然後将方法 組合起來解決當下問題。
文章用下班時間肝了一周才寫完,看完點贊、轉發 是對我最大的支援。
周遊數組方法
不會改變原數組的周遊方法
forEach()
forEach()
forEach()
方法按照升序為數組中每一項執行一次給定的函數。
文法
arr.forEach(callback(currentValue , index , array) ,thisArg)
-
: 數組目前項值currentValue
-
: 數組目前項索引index
-
: 數組對象本身arr
-
: 可選參數。當執行回調函數thisArg
時,用作callback
的值。this
注意
- 如果使用 箭頭函數表達式來傳入函數參數,
參數會被忽略,因為箭頭函數在詞法上綁定了thisArg
值。this
-
不會直接改變調用它的對象,但是那個對象可能會被forEach
函數改變。callback
-
不會改變原數組。every
//防盜貼:微信公衆号: 前端自學社群
const arr = [2,3,4,1,44]
arr.forEach(val =>{
console.log(`值為${val*2}`)
})
console.log(`原數組為${arr}`);
// 值為4
// 值為6
// 值為8
// 值為2
// 值為88
// 原數組為2,3,4,1,44
reduce()
reduce()
reduce()
數組元素累計器,傳回一個合并的結果值。
arr.reduce(callback(accumulator, currentValue, index, array), initialValue)
-
: 累計器,預設為數組元素第一個值accumulator
-
: 目前值currentValue
-
: 目前元素索引 可選index
-
: 數組 可選array
-
: 初始值 可選initialValue
reduce
有兩個參數,一個是回調函數,一個是初始值。
它有兩種取值情況:
-
- 當提供了
初始值時, 那麼initialValue
的值為accumulator
,initialValue
currentValue
數組第一個值
- 當提供了
-
- 當沒有提供
initialValue
的值 為 數組第一個值,accumulator
為第二個值。currentValue
- 當沒有提供
- 如果數組為空,且沒有提供
初始值時,會抛出initialValue
.TypeError
- 如果數組有一個元素,且沒有提供
或者 提供了initialValue
,數組為空,那麼唯一值被傳回不會執行initialValue
回調函數。callback
求和
//防盜貼:微信公衆号: 前端自學社群/
const arr = [1, 2, 3, 4]
const sum = arr.reduce((accumulator, currentValue) => accumulator + currentValue, 10)
console.log(sum) //20
// accumulator 累計器
// currentValue 目前值
// initialValue 累計 初始值 為10
//10 + 1 + 2 + 3 + 4
## 注意
// 回調函數第一次執行時,accumulator 和currentValue的取值有兩種情況:
// 如果調用reduce()時提供了initialValue,accumulator取值為initialValue,currentValue取數組中的第一個值;
// 如果沒有提供 initialValue,那麼accumulator取數組中的第一個值,currentValue取數組中的第二個值。
計算對象中的值
要累加對象數組中包含的值,必須提供初始值,以便各個item正确通過你的函數。
/*
* @Description:
* @Author: 微信公衆号: 前端自學社群
* @Date: 2021-08-07 00:53:51
* @LastEditTime: 2021-08-07 00:53:51
* @LastEditors: Do not edit
*/
const data = [
{
date: '2021-8-1',
income: 200
},
{
date: '2021-8-2',
income: 400
},
{
date: '2021-8-3',
income: 300
},
]
console.log(`總收入: ${data.reduce( (pre,currentValue) => pre + currentValue.income,0)}`);
//總收入: 900
二維數組轉一位數組
const array = [[1,2],[3,4]]
console.log(array.reduce((a,b) => a.concat(b)));
//[ 1, 2, 3, 4 ]
find()
find()
find()
傳回滿足特定條件的元素對象或者元素值, 不滿足傳回
undefined
arr.find((element,index,array), thisArg)
-
: 目前元素element
-
: 目前元素索引 可選index
-
: 數組本身 可選array
-
: 執行回調時用作thisArg
的對象。 可選this
// 從資料中找出第一個滿足特定條件的對象
const data = [
{
name:'張三',
article: 3
},
{
name:'老王',
article: 9
},
{
name:'老李',
article: 10
}
]
console.log(data.find(item => item.article > 9 ));
// { name: '老李', article: 10 }
findIndex()
findIndex()
findIndex()
傳回數組中符合條件的第一個元素的索引,沒有,則傳回
-1
。
arr.findIndex((element,index,array), thisArg)
-
element
-
index
-
array
-
thisArg
this
const arr = [22,33,44,55]
console.log(arr.findIndex(val => val > 33)); //2
console.log(arr.findIndex(val => val > 99)); //-1
key()
key()
key()
傳回一個新的Array Iterator對象,該對象包含數組中每個索引的鍵。
keys()
- 如果數組中有空原元素,在擷取key 時, 也會加入周遊的隊列中。
const inputModal = [
{
name:''
},
{
age:''
},
{
hobby:''
}
]
for(const key of inputModal.keys()){
console.log(key)
}
// 0
// 1
// 2
const arr = [1,2,,3]
for(const key of arr.keys()){
console.log(key);
}
// 0
// 1
// 2
// 3
//Object.keys() 方法會傳回一個由一個給定對象的自身可枚舉屬性組成的數組
// 是以 Object.keys(arr) = [ '0', '1', '3' ]
for(const key of Object.keys(arr)){
console.log(key);
}
// 0
// 1
// 3
values()
values()
values()
方法傳回一個新的 Array Iterator 對象,該對象包含數組每個索引的值。
arr.values()
const Color = ['red','yelloe','orange']
for(val of Color.values()){
console.log(val);
}
// red
// yelloe
// orange
<hr/>
傳回 布爾值
every()
every()
every
用來判斷數組内所有元素是否符合某個條件,傳回 布爾值
arr.every(callback(currentValue , index , array) ,thisArg)
-
: 數組目前項值 必須currentValue
-
: 數組目前項索引 可選index
-
: 數組對象本身可選arr
-
thisArg
callback
的值。可選this
- 當所有的元素都符合條件才會傳回
true
-
every
- 若傳入一個空數組,無論如何都會傳回
true
//防盜貼:微信公衆号: 前端自學社群
const arr = [2,3,4,1,44]
console.log(arr.every(val => val > 0 )); //true
console.log(arr.every(val => { val > 2 })) //false
some()
some()
some()
用來判斷數組元素是否符合某個條件,隻要有一個元素符合,那麼傳回
true
arr.some(callback(currentValue , index , array) ,thisArg)
-
currentValue
-
index
-
arr
-
thisArg
callback
this
-
被調用時不會改變數組。some()
- 如果用一個空數組進行測試,在任何情況下它傳回的都是
false
-
在周遊時,元素範圍已經确定,在周遊過程中添加的元素,不會加入到周遊的序列中。some()
const arr = [2,3,4,1,44]
console.log(arr.some(val => val > 2)) //true
console.log([].some(val => val > 2 )); //false
const newList = [11,22,33,44]
console.log(newList.some(val => {
newList.push(55)
newList.push(66)
val > 55
})); //false
不改變原有數組,形成新的數組
filter()
filter()
filter()
用來周遊原數組,過濾拿到符合條件的數組元素,形成新的數組元素。
arr.some(callback(currentValue , index , array) ,thisArg)
-
currentValue
-
index
-
arr
-
thisArg
callback
this
-
不會改變原數組,它傳回過濾後的新數組。filter
-
filter()
const arr = [11,22,33,44,55,66]
console.log(arr.filter(val => val > 44 ))
console.log(`原數組為${arr}`);
// [ 55, 66 ]
// 原數組為11,22,33,44,55,66
map()
map()
map()
建立一個新的數組,其結果是該數組中的每個元素都調用一個提供的函數後傳回的結果。
arr.map(callback(currentValue , index , array) ,thisArg)
-
currentValue
-
index
-
arr
-
thisArg
callback
this
-
不修改調用它的原數組本身map
-
map()
const arr = [1,2,3,4]
console.log(arr.map(val => val*3 )) // [ 3, 6, 9, 12 ]
console.log(arr) // [ 1, 2, 3, 4 ]
數組 CRUD
改變原數組方法
reverse()
reverse()
reverse()
方法将數組中元素的位置颠倒,并傳回該數組。數組的第一個元素會變成最後一個,數組的最後一個元素變成第一個。該方法會改變原數組。
const arr = [1,2,3]
console.log(arr.reverse(11,22,33)) //[ 3, 2, 1 ]
sort()
sort()
sort()
方法采用 原地算法進行排序并傳回數組。預設排序順序是在将元素轉換為字元串,然後比較它們的
UTF-16
代碼單元值序列
原地算法是一個使用輔助的資料結構對輸入進行轉換的算法。但是,它允許有少量額外的存儲空間來儲存輔助變量。當算法運作時,輸入通常會被輸出覆寫。原地算法僅通過替換或交換元素來更新輸入序列。
const arr = [23,11,33,44,1]
console.log(arr.sort()) //[ 1, 11, 23, 33, 44 ]
const arr = [23,11,33,44,1000000000]
console.log(arr.sort())
// [ 1000000000, 11, 23, 33, 44 ]
删除元素
shift()
shift()
shift()
方法從數組中删除第一個元素,并傳回該元素的值。此方法更改數組的長度。
arr.shift()
- 從數組中删除的元素; 如果數組為空則傳回
undefined
const data = [
{
id:1,
name:'前端'
},
{
id:2,
name:'後端'
},
{
id:3,
name:'移動端'
},
{
id:4,
name:'嵌入式開發'
},
]
const deleObj = data.shift()
console.log('==============删除後的元素======================');
console.log(data);
console.log('=================删除後的元素===================');
console.log('===============被删除的元素=====================');
console.log(deleObj);
console.log('================被删除的元素====================');
// ==============删除後的元素======================
// [
// { id: 2, name: '後端' },
// { id: 3, name: '移動端' },
// { id: 4, name: '嵌入式開發' }
// ]
// =================删除後的元素===================
// ===============被删除的元素=====================
// { id: 1, name: '前端' }
// ================被删除的元素====================
pop()
pop()
pop()
方法從數組中删除最後一個元素,并傳回該元素的值。此方法更改數組的長度。
用法和
shift
類似。
arr.pop()
-
undefined
const data = [
{
id:1,
name:'前端'
},
{
id:2,
name:'後端'
},
{
id:3,
name:'移動端'
},
{
id:4,
name:'嵌入式開發'
},
]
const deleObj = data.pop()
console.log(data);
// [
// { id: 1, name: '前端' },
// { id: 2, name: '後端' },
// { id: 3, name: '移動端' }
// ]
console.log(deleObj);
// { id: 4, name: '嵌入式開發' }
splice()
splice()
splice()
方法通過删除或替換現有元素或者原地添加新的元素來修改數組,并以數組形式傳回被修改的内容。此方法會改變原數組。
array.splice(start,deleteCount, [item1,item2....])
-
: 開始的索引start
-
: 删除的個數 可選deleteCount
-
;從開始的索引進行 添加的增加和替換的元素, 可選[item1,item2 .....]
- 由被删除的元素組成的一個數組。如果隻删除了一個元素,則傳回隻包含一個元素的數組。如果沒有删除元素,則傳回空數組。
- 如果隻傳遞了開始的索引位置,則會删除索引後的所有元素對象
const data = [ { id:1, name:'前端' }, { id:2, name:'後端' }, { id:3, name:'移動端' }, { id:4, name:'嵌入式開發' }, ] data.splice(1) console.log(data) // [ { id: 1, name: '前端' } ]
從索引為 2 開始, 删除 1 個數組元素對象,添加兩個數組元素對象
const data = [
{
id:1,
name:'前端'
},
{
id:2,
name:'後端'
},
{
id:3,
name:'移動端'
},
{
id:4,
name:'嵌入式開發'
},
]
data.splice(2,1,...[{id:5,name:'人工智能'},{id:6,name:'大資料開發'}])
console.log(data);
// [
// { id: 1, name: '前端' },
// { id: 2, name: '後端' },
// { id: 5, name: '人工智能' },
// { id: 6, name: '大資料開發' },
// { id: 4, name: '嵌入式開發' }
// ]
增加元素
splice()
splice()
上面已經有介紹
push()
push()
push()
方法将一個或多個元素添加到數組的末尾,并傳回該數組的新長度。
arr.push(element1, ..., elementN)
const data = [
{
id:1,
name:'前端'
},
{
id:2,
name:'後端'
},
]
console.log(data.push({id:3,name:'移動端'})) //3
合并數組
const data = [
{
id:1,
name:'前端'
},
{
id:2,
name:'後端'
},
]
var obj = [
{
id:4,
name:'嵌入式開發'
},
]
// 相當于 data.push({id:4,name:'嵌入式開發'});
Array.prototype.push.apply(data, obj);
console.log(data);
[
{ id: 1, name: '前端' },
{ id: 2, name: '後端' },
{ id: 4, name: '嵌入式開發' }
]
unshift()
unshift()
unshift()
方法将一個或多個元素添加到數組的開頭,并傳回該數組的新長度。
const arr = [1,2,3]
console.log(arr.unshift(11,22,33)) //6
console.log(arr) //[ 11, 22, 33, 1, 2, 3 ]
不改變原數組元素方法
indexOf()
indexOf()
indexOf()
方法傳回可以在數組中找到給定元素的第一個索引,如果不存在,則傳回 -1。
indexOf(searchElement)
indexOf(searchElement, fromIndex)
-
: 要查找的元素searchElement
-
: 按指定的索引進行查找出現的指定元素的第一個索引。 可選fromIndex
- 如果索引大于或等于數組的長度,則傳回-1
- 如果提供的索引值為負數,則将其視為距數組末尾的偏移量
- 如果提供的索引為負數,仍然從前到後搜尋數組
- 如果提供的索引為 0,則将搜尋整個數組。
- 預設值:0(搜尋整個數組)。
const arr = [1,1,2,3,4,5,4,4,6]
console.log(arr.indexOf(3)); //3
console.log(arr.indexOf(9)); //-1
console.log(arr.indexOf(3,4)); //-1
//從索引為 4 的元素進行查找 3, 顯然後面沒有3 , 傳回 -1
數組去重
建立一個新的空數組,通過
indexOf
來判斷空數組是否第一次存在某個元素,
- 不存在則傳回 [ < 0 ] ,
到空數組中.push
const newArr = []
arr.forEach(val => {
if(newArr.indexOf(val) < 0){
newArr.push(val)
}
})
console.log(newArr);
// [ 1, 2, 3, 4, 5, 6 ]
lastIndexOf()
lastIndexOf()
lastIndexOf()
查找數組中元素最後一次出現的索引,如未找到傳回-1。
如果不存在則傳回 -1。從數組的後面向前查找,從
fromIndex
處開始。
arr.lastIndexOf(searchElement, fromIndex)
-
searchElement
-
fromIndex
- 從指定的索引位置 逆向 查找
- 預設為數組的長度減 1(
),即整個數組都被查找。arr.length - 1
- 如果該值大于或等于數組的長度,則整個數組會被查找。
- 如果為負值,數組仍然會被從後向前查找。
- 如果該值為負時,其絕對值大于數組長度,則方法傳回 -1,即數組不會被查找。
-
使用的是 嚴格相等 === 比較lastIndexOf
和數組中的元素。searchElement
const arr = [1,1,2,3,4,5,4,4,6]
console.log(arr.lastIndexOf(4)); //7
console.log(arr.lastIndexOf(4,11));
//7 指定的查找的索引 大于 數組的長度, 會進行整個數組查找
console.log(arr.lastIndexOf(4,-33));
// -1 指定的索引為負數,且絕對值大于數組長度, 則傳回 -1
console.log(arr.lastIndexOf(4,-5));
//4 指定的索引為負數,且絕對值小于數組長度, 則會 從向前進行查找
inCludes()
inCludes()
includes()
方法用來判斷一個數組是否包含一個指定的值,根據情況,如果包含則傳回 true,否則傳回false。
arr.includes(searchElement, fromIndex)
-
searchElement
查找時,區分大小寫
-
fromIndex
- 從指定的索引進行查找
- 如果為負值,則按升序從
的索引開始搜array.length + fromIndex
- 如果
大于等于數組的長度,則會傳回fromIndex
,且該數組不會被搜尋。false
- 預設為0
const arr = [1,1,2,3,4,5,4,4,6]
console.log(arr.includes(4)); //true
console.log(arr.includes(4,66)); //false
console.log(arr.includes(1,-1)); //false
concat()
concat()
concat()
方法用于合并兩個或多個數組。
var new_array = old_array.concat([arr1][arr2])
-
方法不會改變concat
或任何作為參數提供的數組,而是傳回一個淺拷貝,它包含與原始數組相結合的相同元素的副本this
- 對象引用(而不是實際對象):
将對象引用複制到新數組中。 原始數組和新數組都引用相同的對象。 也就是說,如果引用的對象被修改,則更改對于新數組和原始數組都是可見的。 這包括也是數組的數組參數的元素。concat
- 資料類型如字元串,數字和布爾(不是
,String
和Number
) 對象):Boolean
将字元串和數字的值複制到新數組中。concat
- 對象引用(而不是實際對象):
let arr1 = [1,2,3]
let arr2 = [4,5,6]
let arr3 = [[1,2],[3,4]]
console.log(arr1.concat(arr2));
//[ 1, 2, 3, 4, 5, 6 ]
// 嵌套合并
console.log(arr1.concat(arr2).concat(arr3));
// [ 1, 2, 3, 4, 5, 6, [ 1, 2 ], [ 3, 4 ] ]
let obj1 = [{a:1},{b:2}]
let obj2 = [{c:3},{d:4}]
let obj3 = obj1.concat(obj2)
console.log(obj3);
//[ { a: 1 }, { b: 2 }, { c: 3 }, { d: 4 } ]
obj1[0].a = 4 //改變obj[0]對象值,會直接影響合并後的數組,因為是淺拷貝
console.log(obj3);
//[ { a: 4 }, { b: 2 }, { c: 3 }, { d: 4 } ]
toString()
toString()
toString()
傳回一個字元串,表示指定的數組及其元素。
當一個數組被作為文本值或者進行字元串連接配接操作時,将會自動調用其
toString
方法。
對于數組對象,
toString
方法連接配接數組并傳回一個字元串,其中包含用逗号分隔的每個數組元素。
arr.toString()
const arr = [1,2,3]
console.log(arr.toString()); //1,2,3
join()
join()
join()
方法通過連接配接數組元素用逗号或指定的分隔符字元串分隔,傳回一個字元串。
如果數組隻有一項,則将在不使用分隔符的情況下傳回該項。
join()
join(separator)
-
: 指定的分割的 字元 可選separator
const arr = ['2021','08','08']
console.log(arr.join()); //2021,08,08
console.log(arr.join('-')); //2021-08-08
console.log(arr.join('/')); //2021/08/08
slice()
slice()
slice()
方法傳回一個新的數組對象,這一對象是一個由
begin
end
決定的原數組的淺拷貝(包括
begin
,不包括
end
)。原始數組不會被改變。
arr.slice(begin, end)
-
: 指定截取的開始索引 可選begin
- 預設從0 開始
-
為負數,則以數組末尾開始 的 絕對值開始截取begin
末尾第2個元素slice(-2)
-
超出原數組的索引範圍,則會傳回空數組。begin
-
: 指定截取的結束索引 可選end
-
被省略,則end
會一直提取到原數組末尾。slice
-
大于數組的長度,end
也會一直提取到原數組末尾。slice
-
為負數, 則它表示在原數組中的倒數第幾個元素結束抽取。end
-
const arr = [11,22,33,44,55,66,77,88]
console.log(arr.slice(1,4));
// 應該傳回 索引 1 - 3 的數組元素
// [ 22, 33, 44 ]
console.log(arr.slice(-4,2)) //[]
console.log(arr.slice(-4)); //[ 55, 66, 77, 88 ]
console.log(arr.slice(0,-1));
// [
// 11, 22, 33, 44,
// 55, 66, 77
// ]
參考文獻
Array - JavaScript | MDN最後
文章用下班時間肝了一周,寫作不易,文中的内容都是 參考 MDN 文檔 。
如果喜歡的話可以點贊👍👍👍關注,支援一下,希望大家可以看完本文有所收獲 !