我正在寻找以下方法的任何替代方法,以创建包含1到N的JavaScript数组,其中N仅在运行时已知。

var foo = [];

for (var i = 1; i <= N; i++) {
   foo.push(i);
}

对我来说,我觉得应该有一种不用循环的方法。


当前回答

var foo=Array.from(数组(N),(v,i)=>i+1);

其他回答

我能想出的最简洁的办法是:

[...''.padEnd(N)].map((_,i)=>i+1)

你可以这样做:

var arr=数组.from(数组(10).keys())arr.shift()控制台日志(arr)

Array.prototype.fill()

a = Object.keys( [].fill.call({length:7}, '' ) ).map(Number)
a.pop();
console.debug(a)

[0, 1, 2, 3, 4, 5, 6]

对我来说,这是更有用的实用程序:

/**
 * 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;
};

尝试在Number的原型中添加迭代器。

Number.prototype[Symbol.iterator] = function *(){
  let i = 0;
  while(i < this) yield i++;
  return;
}

现在数字是可迭代的,只需将一个数字传递给Array.from

Array.from(10);//[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

或者任何其他需要迭代的地方,比如。。。循环。

for(const number of 10) console.log(number);//logs 0 through 9 sequentially

这有点复杂,但也很酷。