我正在寻找以下方法的任何替代方法,以创建包含1到N的JavaScript数组,其中N仅在运行时已知。
var foo = [];
for (var i = 1; i <= N; i++) {
foo.push(i);
}
对我来说,我觉得应该有一种不用循环的方法。
我正在寻找以下方法的任何替代方法,以创建包含1到N的JavaScript数组,其中N仅在运行时已知。
var foo = [];
for (var i = 1; i <= N; i++) {
foo.push(i);
}
对我来说,我觉得应该有一种不用循环的方法。
当前回答
嗯,简单但重要的问题。Functional JS在Array对象下肯定缺少一个通用的展开方法,因为我们可能需要创建一个数字项数组,不仅是简单的[1,2,3,…,111],而且是一个函数产生的序列,可能是x=>x*2而不是x=>x
目前,要执行这项工作,我们必须依赖Array.prototype.map()方法。然而,为了使用Array.prototype.map(),我们需要提前知道数组的大小。还是。。如果我们不知道大小,那么我们可以使用Array.prototype.reduce(),但Array.protocol.reduce)用于缩小(折叠)而不是展开正确。。?
显然,我们需要函数JS中的Array.unfold()工具。这是我们可以简单地自己实现的;
Array.unfold = function(p,f,t,s){
var res = [],
runner = v => p(v,res.length-1,res) ? [] : (res.push(f(v)),runner(t(v)), res);
return runner(s);
};
数组展开(p,f,t,v)采用4个参数。
p这是一个定义停止位置的函数。与许多数组函子一样,p函数接受3个参数。值、索引和当前生成的数组。它应返回布尔值。当它返回true时,递归迭代停止。f这是一个返回下一项函数值的函数。t这是一个函数,用于返回下一个参数,以便在下一个回合中提供给f。s是种子值,用于通过f计算索引0的舒适座椅。
因此,如果我们打算创建一个数组,其中包含一个像1,4,9,16,25…n^2这样的序列,我们可以简单地这样做。
Array.unfold=函数(p,f,t,s){var res=[],转轮=v=>p(v,res.length-1,res)?[]:(res.push(f(v)),runner(t(v),res);回流流道;};var myArr=数组展开((_,i)=>i>=9,x=>Math.pow(x,2),x=>x+1,1);console.log(myArr);
其他回答
试试这个
[…Array.from({length:30}).keys()]
对我来说,这是更有用的实用程序:
/**
* create an array filled with integer numbers from base to length
* @param {number} from
* @param {number} to
* @param {number} increment
* @param {Array} exclude
* @return {Array}
*/
export const count = (from = 0, to = 1, increment = 1, exclude = []) => {
const array = [];
for (let i = from; i <= to; i += increment) !exclude.includes(i) && array.push(i);
return array;
};
使用递归的ES6解决方案。不同于所有其他解决方案
const range = (n, A = []) => (n === 1) ? [n, ...A] : range(n - 1, [n, ...A]);
console.log(range(5));
只是另一个ES6版本。
通过使用Array.from第二个可选参数:
Array.from(arrayLike[,mapFn[,thisArg]])
我们可以从空数组(10)位置构建编号数组:
Array.from(Array(10), (_, i) => i)
var arr=数组.来自(数组(10),(_,i)=>i);文档.写入(arr);
https://stackoverflow.com/a/49577331/8784402
使用Delta
对于javascript
smallest and one-liner[...Array(N)].map((v, i) => from + i * step);
示例和其他备选方案
Array.from(Array(10).keys()).map(i => 4 + i * 2);
//=> [4, 6, 8, 10, 12, 14, 16, 18, 20, 22]
[...Array(10).keys()].map(i => 4 + i * -2);
//=> [4, 2, 0, -2, -4, -6, -8, -10, -12, -14]
Array(10).fill(0).map((v, i) => 4 + i * 2);
//=> [4, 6, 8, 10, 12, 14, 16, 18, 20, 22]
Array(10).fill().map((v, i) => 4 + i * -2);
//=> [4, 2, 0, -2, -4, -6, -8, -10, -12, -14]
[...Array(10)].map((v, i) => 4 + i * 2);
//=> [4, 6, 8, 10, 12, 14, 16, 18, 20, 22]
Range Function
const range = (from, to, step) =>
[...Array(Math.floor((to - from) / step) + 1)].map((_, i) => from + i * step);
range(0, 9, 2);
//=> [0, 2, 4, 6, 8]
// can also assign range function as static method in Array class (but not recommended )
Array.range = (from, to, step) =>
[...Array(Math.floor((to - from) / step) + 1)].map((_, i) => from + i * step);
Array.range(2, 10, 2);
//=> [2, 4, 6, 8, 10]
Array.range(0, 10, 1);
//=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Array.range(2, 10, -1);
//=> []
Array.range(3, 0, -1);
//=> [3, 2, 1, 0]
As Iterators
class Range {
constructor(total = 0, step = 1, from = 0) {
this[Symbol.iterator] = function* () {
for (let i = 0; i < total; yield from + i++ * step) {}
};
}
}
[...new Range(5)]; // Five Elements
//=> [0, 1, 2, 3, 4]
[...new Range(5, 2)]; // Five Elements With Step 2
//=> [0, 2, 4, 6, 8]
[...new Range(5, -2, 10)]; // Five Elements With Step -2 From 10
//=>[10, 8, 6, 4, 2]
[...new Range(5, -2, -10)]; // Five Elements With Step -2 From -10
//=> [-10, -12, -14, -16, -18]
// Also works with for..of loop
for (i of new Range(5, -2, 10)) console.log(i);
// 10 8 6 4 2
As Generators Only
const Range = function* (total = 0, step = 1, from = 0) {
for (let i = 0; i < total; yield from + i++ * step) {}
};
Array.from(Range(5, -2, -10));
//=> [-10, -12, -14, -16, -18]
[...Range(5, -2, -10)]; // Five Elements With Step -2 From -10
//=> [-10, -12, -14, -16, -18]
// Also works with for..of loop
for (i of Range(5, -2, 10)) console.log(i);
// 10 8 6 4 2
// Lazy loaded way
const number0toInf = Range(Infinity);
number0toInf.next().value;
//=> 0
number0toInf.next().value;
//=> 1
// ...
带步长/增量的从到
using iteratorsclass Range2 {
constructor(to = 0, step = 1, from = 0) {
this[Symbol.iterator] = function* () {
let i = 0,
length = Math.floor((to - from) / step) + 1;
while (i < length) yield from + i++ * step;
};
}
}
[...new Range2(5)]; // First 5 Whole Numbers
//=> [0, 1, 2, 3, 4, 5]
[...new Range2(5, 2)]; // From 0 to 5 with step 2
//=> [0, 2, 4]
[...new Range2(5, -2, 10)]; // From 10 to 5 with step -2
//=> [10, 8, 6]
using Generators
const Range2 = function* (to = 0, step = 1, from = 0) {
let i = 0,
length = Math.floor((to - from) / step) + 1;
while (i < length) yield from + i++ * step;
};
[...Range2(5, -2, 10)]; // From 10 to 5 with step -2
//=> [10, 8, 6]
let even4to10 = Range2(10, 2, 4);
even4to10.next().value;
//=> 4
even4to10.next().value;
//=> 6
even4to10.next().value;
//=> 8
even4to10.next().value;
//=> 10
even4to10.next().value;
//=> undefined
对于字体
class _Array<T> extends Array<T> {
static range(from: number, to: number, step: number): number[] {
return Array.from(Array(Math.floor((to - from) / step) + 1)).map(
(v, k) => from + k * step
);
}
}
_Array.range(0, 9, 1);