Kulbhushan在开发过程中,了解JavaScript和Promise的基础知识将有助于提高我们的编码技能。今天,让我们来看看以下10个片段。我相信阅读这10个片段将有助于我们对Promise的理解。在本教程中,让我们学习如何使用Array.splice()方法将数组分成相等的部分。我们还将讨论Array.splice()和Array.slice()之间的区别。1.将数组分成两等分我们可以分两步将数组分成两半:使用length/2和Math.ceil()方法找到数组的中间索引使用中间索引和Array.splice()方法获取数组的等分部分Math.ceil()函数返回大于或等于给定数的最小整数。constlist=[1,2,3,4,5,6];constmiddleIndex=Math.ceil(list.length/2);constfirstHalf=list.splice(0,middleIndex);constsecondHalf=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个元素并返回它。在这两个操作结束时,由于我们已经移除了数组中的所有元素,所以原来的数组是空的。另请注意,在上述情况下,元素的数量是偶数,如果元素的数量是奇数,则前半部分将有一个额外的元素。constlist=[1,2,3,4,5];constmiddleIndex=Math.ceil(list.length/2);list.splice(0,middleIndex);//返回[1,2,3]list.splice(-middleIndex);//returns[4,5]2.Array.sliceandArray.splice有时候我们不想改变原来的数组,这可以用Array.slice()来解决:constlist=[1,2,3,4,5,6];constmiddleIndex=Math.ceil(list.length/2);constfirstHalf=list.slice().splice(0,middleIndex);constsecondHalf=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.将数组分成三份constlist=[1,2,3,4,5,6,7,8,9];constthreePartIndex=Math.ceil(list.length/3);constthirdPart=list.splice(-threePartIndex);constsecondPart=list.splice(-threePartIndex);constfirstPart=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],在这次列表只包含前6个元素[1,2,3,4,5,6]。接下来,使用list.splice(-threePartIndex)提取第二部分,它从剩余列表中移除最后3个=[1,2,3,4,5,6](即[4,5,6])元素,列表只包含前三个元素[1,2,3],即firstPart。4.Array.splice()的更多用法现在,让我们看一下Array.splice()的更多用法。因为不想改变原来的数组,所以使用Array.slice()。如果智米要改,原来的阵法可以去掉。constlist=[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]作者:AshishLahoti译者:前端小智来源:jamesknelson原文:https://codingnconcepts.com/javascript/how-to-divide-array-in-equal-parts-in-javascript/本文转载自微信公众号《伟大的走向世界》,你可以通过以下二维码关注。转载本文请联系大千世界公众号。
