javascript - 创建简单的动态数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10451893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:21:30  来源:igfitidea点击:

javascript - Create Simple Dynamic Array

javascript

提问by Sam

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

假设我们可以从变量中得到数字 10

var mynumber = 10;

回答by Nadh

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

回答by ajax333221

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);

所以我创建了数组 new Array(mynumber);

回答by Just About Jeff

With ES2015, this can be achieved concisely in a single expression using the Array.frommethod like so:

使用ES2015,这可以使用如下Array.from方法在单个表达式中简洁地实现:

Array.from({ length: 10 }, (_, idx) => `${++idx}`)

The first argument to fromis an array like object that provides a length property. The second argument is a map function that allows us to replace the default undefinedvalues with their adjusted index values as you requested. Checkout the specification here

的第一个参数from是一个类似数组的对象,它提供了一个长度属性。第二个参数是一个 map 函数,它允许我们undefined根据您的要求用它们调整后的索引值替换默认值。在此处查看规格

回答by Anton Temchenko

This answer is about "how to dynamically create an array without loop".

这个答案是关于“如何动态创建一个没有循环的数组”。

Literal operator []doesn't allow us to create dynamically, so let's look into Array, it's constructor and it's methods.

文字运算符[]不允许我们动态创建,所以让我们看看Array,它是构造函数和方法。

In ES2015 Array has method .from(), which easily allows us to create dynamic Array:

在 ES2015 Array 中有 method .from(),它允许我们轻松地创建动态数组:

Array.from({length: 10}) // -> [undefined, undefined, undefined, ... ]

When Array's constructor receives number as first parameter, it creates an Array with size of that number, but it is not iterable, so we cannot use .map(), .filter()etc. :

当 Array 的构造函数接收 number 作为第一个参数时,它会创建一个具有该数字大小的 Array,但它不可迭代,因此我们不能使用.map(), .filter()etc. :

new Array(10) // -> [empty × 10]

But if we'll pass more than one parameter we will receive array from all parameters:

但是如果我们传递多个参数,我们将从所有参数接收数组:

new Array(1,2,3) // -> [1,2,3]

If we would use ES2015 we can use spread operator which will spread empty Array inside another Array, so we will get iterable Array :

如果我们使用 ES2015,我们可以使用扩展运算符,它将空数组扩展到另一个数组中,因此我们将获得可迭代的数组:

[...new Array(10)]  // -> [undefined, undefined, undefined, ...]

But if we don't use ES2015 and don't have polyfills, there is also a way to create dynamic Array without loop in ES5. If we'll think about .apply()method: it spreads second argument array to params. So calling apply on Array's constructor will do the thing:

但是如果我们不使用 ES2015 并且没有 polyfills,那么在 ES5 中还有一种方法可以创建无循环的动态数组。如果我们考虑.apply()方法:它将第二个参数数组传播到 params。因此,在 Array 的构造函数上调用 apply 将执行以下操作:

Array.apply(null, new Array(10))  // -> [undefined, undefined, undefined, ...]

After we have dynamic iterable Array, we can use map to assign dynamic values:

有了动态可迭代数组后,我们可以使用 map 来分配动态值:

Array.apply(null, new Array(10)).map(function(el, i) {return ++i + ""})

// ["1","2","3", ...]

回答by koblas

Sounds like you just want to construct an array that contains the string versions of the integer values. A simple approach:

听起来您只想构造一个包含整数值的字符串版本的数组。一个简单的方法:

var arr = [];
for (var i = 1; i <= mynumber; i++) arr.push(""+i);

For a more interesting version you could do a generator...

对于更有趣的版本,你可以做一个生成器......

function tail(i, maxval) {
    return [i].concat(i < maxval ? tail(i+1, maxval) : []);
}

var arr = tail(1, mynumber);

回答by David Hellsing

var arr = [];
while(mynumber--) {
    arr[mynumber] = String(mynumber+1);
}

回答by Redu

I would do as follows;

我会这样做;

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

回答by KooiInc

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 Arraylike this:

只是为了好玩,如果你Array像这样扩展:

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;});

回答by Explosion Pills

If you are asking whether there is a built in Pythonic range-like function, there isn't. You have to do it the brute force way. Maybe rangywould be of interest to you.

如果您问是否有内置的类似 Pythonicrange的函数,则没有。你必须以蛮力的方式做到这一点。也许rangy会引起你的兴趣。

回答by Vlad

I had a similar problem and a solution I found (forgot where I found it) is this:

我遇到了类似的问题,我找到的解决方案(忘记在哪里找到的)是这样的:

Array.from(Array(mynumber), (val, index) => index + 1)

Array.from(Array(mynumber), (val, index) => index + 1)