您好,欢迎访问一九零五行业门户网

JavaScript 中实现等分数组

javascript栏目介绍如何实现等分数组
相关免费学习推荐:javascript(视频)
在本教程中,我们来学习一下如何使用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。
以上就是javascript 中实现等分数组的详细内容。
其它类似信息

推荐信息