作者:Ashish Lahoti
譯者:前端小智
來源:jamesknelson
最近開源了一個 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]
代碼部署后可能存在的BUG沒法實時知道,事后為了解決這些BUG,花了大量的時間進行log 除錯,這邊順便給大家推薦一個好用的BUG監控工具 Fundebug,
原文:https://codingnconcepts.com/javascript/how-to-divide-array-in-equal-parts-in-javascript/
交流
文章每周持續更新,可以微信搜索**【大遷世界 】第一時間閱讀,回復【福利】**有多份前端視頻等著你,本文 GitHub https://github.com/qq449245884/xiaozhi 已經收錄,歡迎Star,
CSDN認證博客專家
TypeScript
ECMAScript 6
前端框架
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/232590.html
標籤:其他
上一篇:Vue路由
