利用JavaScript怎么实现一个等分数组

发布时间:2020-12-14 14:12:11 作者:Leah
来源:亿速云 阅读:374

本篇文章给大家分享的是有关利用JavaScript怎么实现一个等分数组,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

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() 方法会先对数组一份拷贝,在操作。

在这两个操作结束时,由于我们已经从数组中删除了所有元素,所以原始数组是空的。

另请注意,在上述情况下,元素数为偶数,如果元素数为奇数,则前一半将有一个额外的元素。

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]

简单解释一下上面做了啥:

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]

以上就是利用JavaScript怎么实现一个等分数组,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

推荐阅读:
  1. JavaScript如何利用indexOf实现数组去重
  2. python将数组n等分的实例

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

javascript 等分数组 avascript

上一篇:利用Goland 怎么生成一个可执行文件

下一篇:台式机装蓝牙模块的方法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》