如何在 JavaScript 中等分數組

做者:Ashish Lahoti
譯者:前端小智
來源:jamesknelson
點贊再看,微信搜索 【大遷世界】關注這個沒有大廠背景,但有着一股向上積極心態人。本文 GitHub https://github.com/qq44924588... 上已經收錄,文章的已分類,也整理了不少個人文檔,和教程資料。**

最近開源了一個 Vue 組件,還不夠完善,歡迎你們來一塊兒完善它,也但願你們能給個 star 支持一下,謝謝各位了。javascript

github 地址:https://github.com/qq44924588...前端

在本教程中,咱們來學習一下如何使用Array.splice()方法將數組等分,還會講一下,Array.splice()Array.slice() 它們之間的不一樣之處。vue

1. 將數組分爲兩個相等的部分

咱們能夠分兩步將數組分紅兩半:java

  1. 使用length/2Math.ceil()方法找到數組的中間索引
  2. 使用中間索引和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個元素並返回它。

在這兩個操做結束時,因爲咱們已經從數組中刪除了全部元素,因此原始數組是空的。git

另請注意,在上述狀況下,元素數爲偶數,若是元素數爲奇數,則前一半將有一個額外的元素。github

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]

簡單解釋一下上面作了啥:ide

  1. 首先使用st.splice(-threePartIndex)提取了ThirdPart,它刪除了最後3個元素[七、八、9],此時list僅包含前6個元素[一、二、三、四、五、6]
  2. 接着,使用list.splice(-threePartIndex)提取了第二部分,它從剩餘list = [一、二、三、四、五、6](即[四、五、6])中刪除了最後3個元素,list僅包含前三個元素[一、二、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]

代碼部署後可能存在的BUG無法實時知道,過後爲了解決這些BUG,花了大量的時間進行log 調試,這邊順便給你們推薦一個好用的BUG監控工具 Fundebug

原文:https://codingnconcepts.com/j...

交流

文章每週持續更新,能夠微信搜索【大遷世界 】第一時間閱讀,回覆【福利】有多份前端視頻等着你,本文 GitHub https://github.com/qq449245884/xiaozhi 已經收錄,歡迎Star。

clipboard.png

相關文章
相關標籤/搜索