在本教程中,我们将学习将数组元素移动到另一个位置的插入策略。
使用 array-move 方法可以处理该问题,该方法返回一个新数组,并将项目移动到新位置:
function arrMove(arr, oldIndex, newIndex) { if (newIndex >= arr.length) { let i = newIndex - arr.length + 1; while (i--) { arr.push(undefined); } } arr.splice(newIndex, 0, arr.splice(oldIndex, 1)[0]); return arr; }; //returns [22, 11, 33] console.log(arrMove([11, 22, 33], 0, 1));
最后返回用于测试目的。
splice() 方法就地对数组执行操作,因此不需要返回。
如果你想避免它并返回一个副本,你可以使用 slice() 方法。
如果 newIndex 大于数组长度,则应使用 new undefined 填充数组。
它会在数组上推送 undefined 直到你有合适的长度。
然后你应该拼接旧的项目。
splice() 方法返回在数组中拼接出来的项目。
由于在给定的示例中,这是 [1],我们应该使用该数组的第一个索引来获取原始 1.
然后你应该使用 splice() 在 newIndex 的位置插入这个项目。
由于我们已经填充了数组,它会出现在正确的位置。
对于负索引,请使用以下代码:
function arrayMove(arr, oldIndex, newIndex) { while (oldIndex < 0) { oldIndex += arr.length; } while (newIndex < 0) { newIndex += arr.length; } if (newIndex >= arr.length) { let i = newIndex - arr.length + 1; while (i--) { arr.push(undefined); } } arr.splice(newIndex, 0, arr.splice(oldIndex, 1)[0]); return arr; }; //returns [11, 33, 22] console.log(arrayMove([11, 22, 33], -1, -2));
slice() 方法
Array.prototype.slice() 方法返回一个新数组,将索引开始到结束(但不包括结束)的所有项目复制到它,其中开始和结束表示该数组中项目的索引。
原始数组保持不变。
splice() 方法
Array.prototype.splice() 方法通过删除或者替换现有项目或者在适当位置添加新项目来更改数组的内容。
与 slice() 方法不同,slice() 更改原始数组。
日期:2020-06-02 22:16:23 来源:oir作者:oir