猿问

如何按顺序添加元素数组?

我有一个数组:const arr = [1, 2, 5, 10];

我如何将其转换为const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


qq_花开花谢_0
浏览 273回答 3
3回答

千万里不及你

const arr = [1, 2, 5, 10];for(let i = 1; i <= 10; i++) { // Loop from 1 till 10, including 10&nbsp; &nbsp; if (!arr.includes(i)) { // If arr does not include 'i'&nbsp; &nbsp; &nbsp; &nbsp; arr.splice(i - 1, 0, i); // We insert it into the array&nbsp; &nbsp; &nbsp; &nbsp; // -1, because arrays start at 0&nbsp; &nbsp; }}

慕莱坞森

一种无需对迭代次数进行硬编码的简单方法是从数组中获取最小值和最大值,然后在它们之间填充数字。这是做到这一点的一种方法const arr = [1, 2, 5, 10];var highest = Math.max(...arr);var minimum = Math.min(...arr);var output = [];for(var i = minimum; i <= highest; i++){&nbsp; output.push(i);}console.log(output);

慕无忌1623718

您可以采用嵌套while语句并拼接缺失的项目。var array = [1, 2, 5, 10],&nbsp; &nbsp; i = array.length;while (i--) while (array[i - 1] + 1 < array[i]) array.splice(i, 0, array[i] - 1);console.log(...array);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答