阿里云主机折上折
  • 微信号
Current Site:Index > Array Basics

Array Basics

Author:Chuan Chen 阅读数:58212人阅读 分类: JavaScript

What is an Array

An array is one of the most fundamental data structures in JavaScript, used to store ordered collections of elements. Each element has a numeric index, starting from 0. Arrays can contain values of any type, even mixed types.

// Several ways to create arrays
const arr1 = [1, 2, 3];  // Array literal
const arr2 = new Array(1, 2, 3);  // Array constructor
const arr3 = Array.of(1, 2, 3);  // ES6 Array.of method

Basic Array Operations

Accessing Elements

Use square bracket notation to access array elements by index:

const fruits = ['apple', 'banana', 'orange'];
console.log(fruits[0]); // 'apple'
console.log(fruits[2]); // 'orange'

Modifying Elements

Modify array elements by assigning values directly via index:

fruits[1] = 'pear';
console.log(fruits); // ['apple', 'pear', 'orange']

Getting Array Length

Use the length property to get the number of elements in an array:

console.log(fruits.length); // 3

Common Array Methods

Adding/Removing Elements

// Add to end
fruits.push('grape'); 
// Add to beginning
fruits.unshift('kiwi');
// Remove from end
fruits.pop();
// Remove from beginning
fruits.shift();

Merging Arrays

The concat method can merge multiple arrays:

const moreFruits = ['melon', 'peach'];
const allFruits = fruits.concat(moreFruits);

Finding Elements

// Find index
const index = fruits.indexOf('banana');
// Check if included
const hasApple = fruits.includes('apple');

Array Iteration

for Loop

The most basic iteration method:

for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

for...of Loop

A more concise syntax introduced in ES6:

for (const fruit of fruits) {
  console.log(fruit);
}

forEach Method

Built-in array iteration method:

fruits.forEach(function(fruit, index) {
  console.log(index, fruit);
});

Array Transformation Methods

map Method

Creates a new array with the results of calling a provided function on every element:

const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
// doubled: [2, 4, 6]

filter Method

Creates a new array with all elements that pass a test:

const evenNumbers = numbers.filter(num => num % 2 === 0);
// evenNumbers: [2]

reduce Method

Executes a reducer function on each element, resulting in a single output value:

const sum = numbers.reduce((total, num) => total + num, 0);
// sum: 6

Multidimensional Arrays

Arrays in JavaScript can contain other arrays, forming multidimensional arrays:

const matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

// Accessing 2D array elements
console.log(matrix[1][2]); // 6

Array Destructuring

ES6 destructuring assignment syntax makes it easy to extract values from arrays:

const [first, second] = fruits;
console.log(first); // 'apple'
console.log(second); // 'banana'

// Skipping elements
const [,,third] = fruits;
console.log(third); // 'orange'

Spread Operator

ES6 spread operator simplifies array operations:

// Copy array
const fruitsCopy = [...fruits];
// Merge arrays
const combined = [...fruits, ...moreFruits];
// As function arguments
Math.max(...numbers);

Typed Arrays

JavaScript provides typed arrays for handling binary data:

// Create an 8-byte buffer
const buffer = new ArrayBuffer(8);
// Create a view treating buffer as 32-bit integer array
const int32View = new Int32Array(buffer);

Performance Considerations

For large arrays, certain operations may impact performance:

// Inserting at beginning shifts all elements
fruits.unshift('strawberry'); // Poor performance

// Direct assignment via index is faster
fruits[fruits.length] = 'blueberry'; // Better performance

Array-String Conversion

// Array to string
const str = fruits.join(', ');
// String to array
const strToArr = 'a,b,c'.split(',');

Array Static Methods

ES6 added Array static methods:

// Check if array
Array.isArray(fruits);
// Create array from array-like object
Array.from('hello');
// Create array with variable arguments
Array.of(1, 2, 3);

Array Iterator Methods

ES6 added iterator-related methods for arrays:

// Get keys iterator
for (const key of fruits.keys()) {
  console.log(key); // 0, 1, 2
}
// Get values iterator
for (const value of fruits.values()) {
  console.log(value); // 'apple', 'banana', 'orange'
}
// Get key-value pairs iterator
for (const [index, value] of fruits.entries()) {
  console.log(index, value);
}

Array Search Methods

ES6 added search methods:

// Find first matching element
const found = fruits.find(fruit => fruit.length > 5);
// Find first matching index
const foundIndex = fruits.findIndex(fruit => fruit.length > 5);

Array Filling and Inclusion

// Fill array
const filled = new Array(3).fill(0); // [0, 0, 0]
// Check if includes element
const includesBanana = fruits.includes('banana');

Array Flattening

ES2019 added flattening methods:

const nested = [1, [2, [3]]];
// Flatten one level
const flat1 = nested.flat(); // [1, 2, [3]]
// Fully flatten
const flatInf = nested.flat(Infinity); // [1, 2, 3]

Array Sorting

The sort method sorts arrays:

const unsorted = [3, 1, 4, 2];
// Default sort (as strings)
unsorted.sort(); // [1, 2, 3, 4]
// Custom sort
unsorted.sort((a, b) => b - a); // [4, 3, 2, 1]

Arrays vs Objects

While arrays are special types of objects, there are important differences:

typeof []; // 'object'
Array.isArray([]); // true

// Arrays have auto-maintained length property
const arr = [];
arr[100] = 'value';
console.log(arr.length); // 101

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

上一篇:对象基础

下一篇:错误处理机制

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.