Array creation and initialization
In JavaScript, arrays are a fundamental and powerful data structure used to store ordered collections of elements. There are various ways to create and initialize arrays, and mastering these methods can significantly improve development efficiency.
Array Literal Creation
The most straightforward method is using array literal syntax, defining elements within square brackets []
:
// Empty array
const emptyArr = [];
// Array with initial elements
const fruits = ['apple', 'banana', 'orange'];
// Mixed-type array
const mixed = [1, 'text', true, { key: 'value' }];
Using the Array Constructor
Arrays can be created with new Array()
, but special attention is needed for parameter behavior:
// Create an array with 3 empty slots
const arr1 = new Array(3); // [empty × 3]
// Create an array with a single numeric element
const arr2 = new Array(3.5); // [3.5]
// Create a multi-element array
const arr3 = new Array('a', 'b', 'c'); // ['a', 'b', 'c']
ES6's Array.of Method
Resolves ambiguity in constructor parameters:
Array.of(3); // [3]
Array.of(1, 2, 3); // [1, 2, 3]
Array.from Method
Converts array-like objects or iterables into arrays:
// Convert string to array
Array.from('hello'); // ['h', 'e', 'l', 'l', 'o']
// Convert Set to array
Array.from(new Set([1, 2, 2, 3])); // [1, 2, 3]
// With mapping function
Array.from([1, 2, 3], x => x * 2); // [2, 4, 6]
Common Methods for Filling Arrays
Initialization with fill
// Create and fill an array of length 5
const filled = new Array(5).fill(0); // [0, 0, 0, 0, 0]
// Fill within a specified range
const partialFill = ['a', 'b', 'c', 'd'];
partialFill.fill('*', 1, 3); // ['a', '*', '*', 'd']
Initialization with map
// Create a sequence array
const sequence = Array(5).fill().map((_, i) => i + 1); // [1, 2, 3, 4, 5]
// Generate an array of random numbers
const randoms = Array(3).fill().map(() => Math.random());
Multidimensional Array Initialization
Creating 2D arrays requires attention to reference issues:
// Incorrect approach (all rows reference the same array)
const wrongMatrix = new Array(3).fill(new Array(3).fill(0));
// Correct approach
const matrix = Array.from({ length: 3 }, () =>
new Array(3).fill(0)
);
// Initialize a 3D array
const cube = Array.from({ length: 3 }, () =>
Array.from({ length: 3 }, () =>
new Array(3).fill(null)
)
);
Special Array Creation Techniques
Generating Numeric Range Arrays
// Generate an array from 1 to 10
const range1 = [...Array(10).keys()].map(i => i + 1);
// Using a generator function
function* generateRange(start, end) {
for (let i = start; i <= end; i++) yield i;
}
const range2 = [...generateRange(5, 8)]; // [5, 6, 7, 8]
Creating Sparse Arrays
// Explicitly create an array with empty slots
const sparse = [1, , , 4]; // [1, empty × 2, 4]
// Note the difference between empty slots and undefined
const withUndefined = [1, undefined, undefined, 4];
Performance Optimization Tips
For large-scale array initialization, setting length directly is more efficient than using push:
// Efficient approach
const bigArr = [];
bigArr.length = 1000000;
// Inefficient approach
const slowArr = [];
for (let i = 0; i < 1000000; i++) {
slowArr.push(i);
}
Modern JavaScript Features
ES2023 introduced the Array.with()
method for non-destructive array modification:
const original = [1, 2, 3];
const modified = original.with(1, 99); // [1, 99, 3]
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:对象属性检测
下一篇:数组基本操作(增删改查)