如何在 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

相关文章
相关标签/搜索