javascript - Create Simple Dynamic Array

2020-02-24 12:10发布

What's the most efficient way to create this simple array dynamically.

var arr = [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];

Let's say we can get the number 10 from a variable

var mynumber = 10;

标签: javascript
13条回答
够拽才男人
2楼-- · 2020-02-24 13:01

misread the question, corrected. Try:

var myNumber = 100,
    myarr = (function arr(i){return i ? arr(i-1).concat(i) : [i]}(myNumber));

Just for fun, if you extend Array like this:

Array.prototype.mapx = function(callback){
  return String(this).split(',').map(callback);
}

You could use:

var myNum = 100, 
    myarr = new Array(myNum).mapx(function(el,i){return i+1;});
查看更多
登录 后发表回答