Basic array operations (add, delete, modify, query)
Array Creation and Initialization
Arrays are one of the most commonly used data structures in JavaScript, used to store ordered collections of elements. There are multiple ways to create arrays:
// Literal notation
const fruits = ['apple', 'banana', 'orange'];
// Constructor notation
const numbers = new Array(1, 2, 3);
// Create an empty array of specified length
const emptyArray = new Array(5); // Creates an empty array of length 5
Arrays can be initialized with elements of any type:
const mixedArray = [1, 'text', true, {name: 'John'}, [1, 2, 3]];
ES6 introduced the Array.of()
method to avoid ambiguity when using the constructor:
const arr1 = Array.of(7); // [7]
const arr2 = Array(7); // [ , , , , , , ]
Adding Elements to Arrays
There are multiple methods to add elements to an array, each with different use cases:
push()
method - Adds one or more elements to the end of the array:
const colors = ['red', 'green'];
colors.push('blue'); // ['red', 'green', 'blue']
colors.push('yellow', 'purple'); // Adds multiple elements
unshift()
method - Adds one or more elements to the beginning of the array:
const numbers = [2, 3];
numbers.unshift(1); // [1, 2, 3]
numbers.unshift(-1, 0); // [-1, 0, 1, 2, 3]
splice()
method - Inserts elements at a specified position:
const letters = ['a', 'b', 'd'];
letters.splice(2, 0, 'c'); // Inserts 'c' at index 2
// ['a', 'b', 'c', 'd']
concat()
method - Merges arrays:
const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = arr1.concat(arr2); // [1, 2, 3, 4]
The ES6 spread operator can also be used to merge arrays:
const newArray = [...arr1, ...arr2];
Removing Elements from Arrays
Similarly, there are multiple methods to remove elements from arrays:
pop()
method - Removes and returns the last element of the array:
const stack = [1, 2, 3];
const last = stack.pop(); // last = 3, stack = [1, 2]
shift()
method - Removes and returns the first element of the array:
const queue = [1, 2, 3];
const first = queue.shift(); // first = 1, queue = [2, 3]
splice()
method - Removes elements at a specified position:
const items = ['a', 'b', 'c', 'd'];
items.splice(1, 2); // Removes 2 elements starting from index 1
// items = ['a', 'd']
filter()
method - Creates a new array with elements that pass a test:
const numbers = [1, 2, 3, 4, 5];
const evens = numbers.filter(n => n % 2 === 0);
// evens = [2, 4], numbers remains unchanged
delete
operator - Removes an element but leaves the position empty:
const arr = [1, 2, 3];
delete arr[1]; // arr = [1, empty, 3]
Modifying Array Elements
The most straightforward way to modify array elements is by accessing them via index and reassigning:
const fruits = ['apple', 'banana', 'cherry'];
fruits[1] = 'blueberry'; // ['apple', 'blueberry', 'cherry']
The splice()
method can also be used to replace elements:
const colors = ['red', 'green', 'blue'];
colors.splice(1, 1, 'yellow'); // Replaces the element at index 1
// colors = ['red', 'yellow', 'blue']
fill()
method - Fills the array with a static value:
const arr = new Array(3).fill(0); // [0, 0, 0]
const arr2 = [1, 2, 3, 4];
arr2.fill(5, 1, 3); // [1, 5, 5, 4]
map()
method - Creates a new array with the results of calling a function on every element:
const numbers = [1, 2, 3];
const doubled = numbers.map(n => n * 2);
// doubled = [2, 4, 6]
Querying Array Elements
There are multiple methods and techniques for querying array elements:
Index access - The most basic query method:
const fruits = ['apple', 'banana', 'orange'];
const first = fruits[0]; // 'apple'
includes()
method - Checks if an array contains a specific element:
const numbers = [1, 2, 3];
numbers.includes(2); // true
numbers.includes(4); // false
indexOf()
and lastIndexOf()
- Finds the index of an element:
const letters = ['a', 'b', 'c', 'a'];
letters.indexOf('a'); // 0
letters.lastIndexOf('a'); // 3
letters.indexOf('d'); // -1 (not found)
find()
and findIndex()
- Uses a test function to find elements:
const users = [
{id: 1, name: 'John'},
{id: 2, name: 'Jane'}
];
const user = users.find(u => u.id === 2); // {id: 2, name: 'Jane'}
const index = users.findIndex(u => u.id === 2); // 1
some()
and every()
- Tests if elements satisfy a condition:
const nums = [1, 2, 3, 4];
nums.some(n => n > 3); // true (at least one element is greater than 3)
nums.every(n => n > 0); // true (all elements are greater than 0)
Array Iteration Methods
There are multiple ways to iterate over arrays, each with its own advantages and disadvantages:
for
loop - The most basic iteration method:
const arr = ['a', 'b', 'c'];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
for...of
loop - A more concise syntax introduced in ES6:
for (const item of arr) {
console.log(item);
}
forEach()
method - Executes a function for each element:
arr.forEach((item, index) => {
console.log(`${index}: ${item}`);
});
map()
method - Creates a new array:
const lengths = ['a', 'bb', 'ccc'].map(s => s.length);
// lengths = [1, 2, 3]
reduce()
method - Reduces the array to a single value:
const sum = [1, 2, 3, 4].reduce((acc, curr) => acc + curr, 0);
// sum = 10
Sorting and Reversing Arrays
sort()
method - Sorts the elements of an array:
const fruits = ['banana', 'apple', 'pear'];
fruits.sort(); // ['apple', 'banana', 'pear']
const numbers = [10, 2, 5, 1];
numbers.sort(); // [1, 10, 2, 5] (default string sorting)
numbers.sort((a, b) => a - b); // [1, 2, 5, 10] (correct numeric sorting)
reverse()
method - Reverses the order of the array:
const arr = [1, 2, 3];
arr.reverse(); // [3, 2, 1]
Slicing and Joining Arrays
slice()
method - Returns a portion of the array:
const arr = [1, 2, 3, 4, 5];
const part = arr.slice(1, 4); // [2, 3, 4] (excludes the end index)
const copy = arr.slice(); // Creates a shallow copy
join()
method - Joins array elements into a string:
const words = ['Hello', 'world'];
const sentence = words.join(' '); // 'Hello world'
Multidimensional Array Operations
Arrays in JavaScript can contain other arrays, forming multidimensional arrays:
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
// Accessing elements
const middle = matrix[1][1]; // 5
// Iterating over a 2D array
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[i].length; j++) {
console.log(matrix[i][j]);
}
}
// Flattening an array using flat()
const flatArray = matrix.flat(); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
Utility Methods for Arrays
Array.isArray()
- Checks if a variable is an array:
Array.isArray([]); // true
Array.isArray({}); // false
toString()
and toLocaleString()
:
const arr = [1, 'a', new Date()];
arr.toString(); // "1,a,Thu Dec 01 2022..."
arr.toLocaleString(); // Localized string representation
entries()
, keys()
, and values()
- Returns iterators:
const arr = ['a', 'b', 'c'];
for (const [index, value] of arr.entries()) {
console.log(index, value);
}
Performance Considerations for Arrays
Different array operations have different performance characteristics:
push
/pop
operations have O(1) time complexityshift
/unshift
operations have O(n) time complexity because all elements need to be shifted- Accessing elements has O(1) time complexity
- Searching for elements has O(n) time complexity in the worst case
For large arrays, frequent use of shift
/unshift
may cause performance issues. Consider using other data structures like linked lists in such cases.
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn