How can you divide an array in 2 parts, divided exactly in the middle?
如何将数组分为两部分,准确地分成中间部分?
Use the Array instance splice()
method:
使用Array实例的splice()
方法:
const list = [1, 2, 3, 4, 5, 6]
const half = Math.ceil(list.length / 2);
const firstHalf = list.splice(0, half)
const secondHalf = list.splice(-half)
If the list contains an even number of items, the result is split with exactly half the items.
如果列表包含偶数个项目,则结果将被精确地拆分为一半的项目。
If the number is odd, for example
例如,如果数字为奇数
[1, 2, 3, 4, 5]
The result will be
结果将是
[ 1, 2, 3 ]
[ 4, 5 ]
翻译自: https://flaviocopes.com/how-to-cut-array-half-javascript/