1
0
Files
frost-zx.github.io/docs/content/javascript-define-and-init-array.md
2025-10-13 10:20:34 +08:00

60 lines
1.0 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: "JavaScript 创建并初始化任意长度的数组"
date: 2025-02-11T20:45:30Z
lastmod: 2025-02-20T22:59:05Z
tags: [JavaScript,Web 前端]
---
# JavaScript 创建并初始化任意长度的数组
## 直接定义
```javascript
var arr = [0, 0, 0, 0, 0]; // [0, 0, 0, 0, 0]
```
## 使用 push() 方法
```javascript
var arr = [];
for (let i = 0; i < 5; i++) {
arr.push(0);
}
// [0, 0, 0, 0, 0]
```
## 使用 Array 构造函数和 fill() 方法
```javascript
var arr = new Array(5); // [empty × 5]
arr.fill(0); // [0, 0, 0, 0, 0]
```
## 使用 Array 构造函数和数组展开
```javascript
var arr = [...new Array(5)]; // [undefined x 5]
```
```javascript
var arr = [...new Array(5).keys()]; // [0, 1, 2, 3, 4]
```
## 使用 Array.from()
> `Array.from(arrayLike[, mapFn[, thisArg]])`
```javascript
var arr = Array.from({length: 5}); // [undefined x 5]
```
```javascript
var arr = Array.from({length: 5}, () => 0); // [0, 0, 0, 0, 0]
```
```javascript
var arr = Array.from({length: 5}, (v, i) => (i + 1)); // [1, 2, 3, 4, 5]
```