Javascript javascript创建给定大小的空数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34937349/
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-23 17:04:25  来源:igfitidea点击:

javascript create empty array of a given size

javascript

提问by gus

in javascript how would I create an empty array of a given size

在 javascript 中,我将如何创建一个给定大小的空数组

Psuedo code:

伪代码:

X = 3;
createarray(myarray, X, "");

output:

输出:

   myarray = ["","",""]

采纳答案by mariocatch

var arr = new Array(5);
console.log(arr.length) // 5

回答by stpoa

1)To create new array which, you cannot iterate over, you can use array constructor:

1)要创建不能迭代的新数组,可以使用数组构造函数:

Array(100)or new Array(100)

Array(100)或者 new Array(100)


2)You can create new array, which can be iterated overlike below:


2)您可以创建新数组,可以像下面这样迭代

a)All JavaScript versions

a)所有 JavaScript 版本

  • Array.apply: Array.apply(null, Array(100))
  • 数组.应用: Array.apply(null, Array(100))

b)From ES6 JavaScript version

b)从 ES6 JavaScript 版本开始

  • Destructuring operator: [...Array(100)]
  • Array.prototype.fill Array(100).fill(undefined)
  • Array.from Array.from({ length: 100 })
  • 解构运算符: [...Array(100)]
  • 数组.prototype.fill Array(100).fill(undefined)
  • 数组.from Array.from({ length: 100 })

You can map over these arrays like below.

您可以像下面这样映射这些数组。

  • Array(4).fill(null).map((u, i) => i)[0, 1, 2, 3]

  • [...Array(4)].map((u, i) => i)[0, 1, 2, 3]

  • Array.apply(null, Array(4)).map((u, i) => i)[0, 1, 2, 3]

  • Array.from({ length: 4 }).map((u, i) => i)[0, 1, 2, 3]

  • Array(4).fill(null).map((u, i) => i)[0, 1, 2, 3]

  • [...Array(4)].map((u, i) => i)[0, 1, 2, 3]

  • Array.apply(null, Array(4)).map((u, i) => i)[0, 1, 2, 3]

  • Array.from({ length: 4 }).map((u, i) => i)[0, 1, 2, 3]

回答by andrewkslv

We use Array.from({length: 500})since 2017.

我们Array.from({length: 500})从 2017 年开始使用。

回答by guest271314

Try using whileloop, Array.prototype.push()

尝试使用while循环,Array.prototype.push()

var myArray = [], X = 3;
while (myArray.length < X) {
  myArray.push("")
}

Alternatively, using Array.prototype.fill()

或者,使用 Array.prototype.fill()

var myArray = Array(3).fill("");

回答by 7vujy0f0hy

In 2018 and thenceforth we shall use [...Array(500)]to that end.

在 2018 年及以后,我们将[...Array(500)]为此目的使用。

回答by jeffdill2

If you want an empty array of undefinedelements, you could simply do

如果你想要一个空的undefined元素数组,你可以简单地做

var whatever = new Array(5);

this would give you

这会给你

[undefined, undefined, undefined, undefined, undefined]

and then if you wanted it to be filled with empty strings, you could do

然后如果你想用空字符串填充它,你可以这样做

whatever.fill('');

which would give you

这会给你

["", "", "", "", ""]

And if you want to do it in one line:

如果你想在一行中完成:

var whatever = Array(5).fill('');