📅  最后修改于: 2023-12-03 15:39:33.209000             🧑  作者: Mango
在 JavaScript 中,创建从 i
到 j
的数字数组有多种方法。
可以使用 Array.from()
方法创建数字数组。此方法需要两个参数:长度( j - i + 1
)和一个映射函数(这里使用箭头函数实现)。
const i = 1;
const j = 5;
const arr = Array.from({ length: j - i + 1 }, (_, index) => index + i);
console.log(arr); // [1, 2, 3, 4, 5]
还可以使用 Array()
构造函数和 fill()
方法创建数字数组。这种方法需要一个参数:数组长度( j - i + 1
)。
const i = 1;
const j = 5;
const arr = Array(j - i + 1).fill().map((_, index) => index + i);
console.log(arr); // [1, 2, 3, 4, 5]
使用循环也可以形成从 i
到 j
的数字数组。此方法简单直接,适用于较小的数组。
const i = 1;
const j = 5;
const arr = [];
for (let n = i; n <= j; n++) {
arr.push(n);
}
console.log(arr); // [1, 2, 3, 4, 5]
以上三种方法都可以构造从 i
到 j
的数字数组。根据实际需求和性能要求选择更合适的方法即可。