如何在 JavaScript 中等分數組
Kulbhushan 在開發中,了解 JavaScript 和 Promise 基礎,有助于提高我們的編碼技能,今天,我們一起來看看下面的 10 片段,相信看完這 10 個片段有助于我們對 Promise 的理解。
在本教程中,我們來學習一下如何使用Array.splice()方法將數組等分,還會講一下,Array.splice() 和 Array.slice() 它們之間的不同之處。
1. 將數組分為兩個相等的部分
我們可以分兩步將數組分成兩半:
- 使用length/2和Math.ceil()方法找到數組的中間索引
- 使用中間索引和Array.splice()方法獲得數組等分的部分
Math.ceil() 函數返回大于或等于一個給定數字的最小整數。
- const list = [1, 2, 3, 4, 5, 6];
- const middleIndex = Math.ceil(list.length / 2);
- const firstHalf = list.splice(0, middleIndex);
- const secondHalf = list.splice(-middleIndex);
- console.log(firstHalf); // [1, 2, 3]
- console.log(secondHalf); // [4, 5, 6]
- console.log(list); // []
Array.splice() 方法通過刪除,替換或添加元素來更改數組的內容。而 Array.slice() 方法會先對數組一份拷貝,在操作。
- list.splice(0, middleIndex) 從數組的0索引處刪除前3個元素,并將其返回。
- splice(-middleIndex)從數組中刪除最后3個元素并返回它。
在這兩個操作結束時,由于我們已經從數組中刪除了所有元素,所以原始數組是空的。
另請注意,在上述情況下,元素數為偶數,如果元素數為奇數,則前一半將有一個額外的元素。
- const list = [1, 2, 3, 4, 5];
- const middleIndex = Math.ceil(list.length / 2);
- list.splice(0, middleIndex); // returns [1, 2, 3]
- list.splice(-middleIndex); // returns [4, 5]
2.Array.slice 和 Array.splice
有時我們并不希望改變原始數組,這個可以配合 Array.slice() 來解決這個問題:
- const list = [1, 2, 3, 4, 5, 6];
- const middleIndex = Math.ceil(list.length / 2);
- const firstHalf = list.slice().splice(0, middleIndex);
- const secondHalf = list.slice().splice(-middleIndex);
- console.log(firstHalf); // [1, 2, 3]
- console.log(secondHalf); // [4, 5, 6]
- console.log(list); // [1, 2, 3, 4, 5, 6];
我們看到原始數組保持不變,因為在使用Array.slice()刪除元素之前,我們使用Array.slice()復制了原始數組。
3.將數組分成三等分
- const list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
- const threePartIndex = Math.ceil(list.length / 3);
- const thirdPart = list.splice(-threePartIndex);
- const secondPart = list.splice(-threePartIndex);
- const firstPart = list;
- console.log(firstPart); // [1, 2, 3]
- console.log(secondPart); // [4, 5, 6]
- console.log(thirdPart); // [7, 8, 9]
簡單解釋一下上面做了啥:
- 首先使用st.splice(-threePartIndex)提取了ThirdPart,它刪除了最后3個元素[7、8、9],此時list僅包含前6個元素[1、2、3、4、5、6] 。
- 接著,使用list.splice(-threePartIndex)提取了第二部分,它從剩余list = [1、2、3、4、5、6](即[4、5、6])中刪除了最后3個元素,list僅包含前三個元素[1、2、3],即firstPart。
4. Array.splice() 更多用法
現在,我們來看一看 Array.splice() 更多用法,這里因為我不想改變原數組,所以使用了 Array.slice(),如果智米們想改變原數組可以進行刪除它。
- const list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
獲取數組的第一個元素
- list.slice().splice(0, 1) // [1]
獲取數組的前5個元素
- list.slice().splice(0, 5) // [1, 2, 3, 4, 5]
獲取數組前5個元素之后的所有元素
- list.slice().splice(5) // 6, 7, 8, 9]
獲取數組的最后一個元素
- list.slice().splice(-1) // [9]
獲取數組的最后三個元素
- list.slice().splice(-3) // [7, 8, 9]
作者:Ashish Lahoti 譯者:前端小智 來源:jamesknelson
原文:https://codingnconcepts.com/javascript/how-to-divide-array-in-equal-parts-in-javascript/
本文轉載自微信公眾號「大遷世界」,可以通過以下二維碼關注。轉載本文請聯系大遷世界公眾號。