JavaScript 中實現等分陣列

weixin1_43144260發表於2020-12-14

最近開源了一個 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 等分陣列內容請搜尋指令碼之家以

本文只代表個人觀點!
原文連結:http://www.662p.com/article/3145.html

相關文章