如何在JavaScript中等分數組的實現
最近開源了一個 Vue 組件,還不夠完善,歡迎大家來一起完善它,也希望大家能給個 star 支持一下,謝謝各位了。
github 地址:https://github.com/qq449245884/vue-okr-tree
在本教程中,我們來學習一下如何使用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]
到此這篇關于如何在JavaScript中等分數組的實現的文章就介紹到這了,更多相關JavaScript 等分數組內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: