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条回答
\"骚年 ilove
2楼-- · 2020-02-24 12:35

I hope you have to get last element from array variable so my solution

var arr = [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
var mynumber = arr [arr .length - 1];
//var mynumber = 10;
查看更多
Anthone
3楼-- · 2020-02-24 12:39
var arr = [];
for(var i=1; i<=mynumber; i++) {
   arr.push(i.toString());
}
查看更多
爷的心禁止访问
4楼-- · 2020-02-24 12:39
var arr = [];
for(var i=1; i<=mynumber; i++) {
   arr.push("" + i);
}

This seems to be faster in Chrome, according to JSPerf, but please note that it is all very browser dependant.

There's 4 things you can change about this snippet:

  1. Use for or while.
  2. Use forward or backward loop (with backward creating sparse array at beginning)
  3. Use push or direct access by index.
  4. Use implicit stringification or explicitly call toString.

In each and every browser total speed would be combination of how much better each option for each item in this list performs in that particular browser.

TL;DR: it is probably not good idea to try to micro-optimize this particular piece.

查看更多
做自己的国王
5楼-- · 2020-02-24 12:41

Here is how I would do it:

var mynumber = 10;
var arr = new Array(mynumber);

for (var i = 0; i < mynumber; i++) {
    arr[i] = (i + 1).toString();
}

My answer is pretty much the same of everyone, but note that I did something different:

  • It is better if you specify the array length and don't force it to expand every time

So I created the array with new Array(mynumber);

查看更多
Ridiculous、
6楼-- · 2020-02-24 12:41

I would do as follows;

var num = 10,
  dynar = [...Array(num)].map((_,i) => ++i+"");
console.log(dynar);

查看更多
萌系小妹纸
7楼-- · 2020-02-24 12:43
var arr = [];
while(mynumber--) {
    arr[mynumber] = String(mynumber+1);
}
查看更多
登录 后发表回答