在本教程中,我们来学习一下如何使用Array.splice()方法将数组等分,还会讲一下,Array.splice() 和 Array.slice() 它们之间的不同之处。
我们可以分两步将数组分成两半:
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() 方法会先对数组一份拷贝,在操作。
在这两个操作结束时,由于我们已经从数组中删除了所有元素,所以原始数组是空的。
另请注意,在上述情况下,元素数为偶数,如果元素数为奇数,则前一半将有一个额外的元素。
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]
有时我们并不希望改变原始数组,这个可以配合 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()复制了原始数组。
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]
简单解释一下上面做了啥:
现在,我们来看一看 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]
作者:Ashish Lahoti 译者:前端小智 来源:jamesknelson
原文:https://codingnconcepts.com/javascript/how-to-pide-array-in-equal-parts-in-javascript/
页面更新:2024-05-29
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号