掌握 JavaScript 数组:技术、最佳实践和高级用途

2025-06-05

掌握 JavaScript 数组:技术、最佳实践和高级用途

数组是一个特殊的变量,它可以保存多个值:



const name = ["Sakib", "Arif", "Fatema"];


Enter fullscreen mode Exit fullscreen mode

为什么要使用数组?

数组是 JavaScript(以及许多其他编程语言)中的基本数据结构,原因如下:

  1. 组织数据:数组允许你将多个值存储在一个变量中,从而更轻松地管理数据集合。例如,如果你需要跟踪用户名列表,则可以将它们全部存储在一个数组中。

  2. 索引访问:数组提供了一种使用索引访问元素的便捷方式。这使得根据特定元素的位置进行检索或修改变得轻而易举。

  3. 高效迭代:JavaScript 提供了多种迭代数组的方法,例如forforEachmapfilterreduce。这些方法使您能够以最少的代码处理数组的每个元素。

  4. 动态调整大小:JavaScript 中的数组是动态的,这意味着它们可以根据需要增大或缩小大小。您无需预先指定大小,这增加了数据处理方式的灵活性。

  5. 内置方法:JavaScript 数组自带丰富的内置方法,可用于操作和查询数据。诸如pushpopshiftunshiftspliceslice等方法可以简化常见任务。

  6. 灵活的数据处理能力:数组可以存储各种类型的数据,包括数字、字符串、对象,甚至其他类型的数组。这种多功能性使其适用于各种应用场景。

  7. 增强的性能:数组针对 JavaScript 引擎的性能进行了优化,使其能够高效地完成涉及顺序数据处理和操作的任务。

  8. 支持高阶函数:JavaScript 数组旨在与高阶函数无缝协作,从而实现更具表现力和更简洁的代码。诸如mapfilter和 之类的函数reduce支持强大的数据转换和聚合功能。

总之,数组对于在 JavaScript 中高效灵活地组织、访问和操作数据集合至关重要。

创建数组

图片描述

句法



const array_name = [item1, item2, ...]; 


Enter fullscreen mode Exit fullscreen mode

空格和换行符不重要。声明可以跨越多行:



const developer = [
  "Fatema",
  "Sakib",
  "Riaz"
];


Enter fullscreen mode Exit fullscreen mode

您还可以创建一个数组,然后提供元素:



const man = [];
cars[0]= "Abdur Rahman";
cars[1]= "Riyaz Khan";
cars[2]= "Jumman KL";


Enter fullscreen mode Exit fullscreen mode

使用 JavaScript 关键字 new



const man = new Array("Saabid", "Fatema", "Rukhsana");


Enter fullscreen mode Exit fullscreen mode

访问数组元素
您可以通过引用索引号来访问数组元素:



const man = ["Fatema", "Sakib", "Ayesha"];
let car = cars[0];


Enter fullscreen mode Exit fullscreen mode

将数组转换为字符串



const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();


Enter fullscreen mode Exit fullscreen mode

在 JavaScript 中将数组转换为字符串是一种常见的操作,有几种方法可以实现此操作,每种方法都适用于不同的需求。以下是最常用的方法:

1.join()方法

join()方法将数组的所有元素组合成一个字符串,并在元素之间使用指定的分隔符。



const fruits = ['apple', 'banana', 'cherry'];
const result = fruits.join(', '); // 'apple, banana, cherry'
console.log(result);


Enter fullscreen mode Exit fullscreen mode
  • 语法array.join([separator])
  • 默认分隔符:(,逗号)
  • 自定义分隔符:您可以指定任何字符串作为分隔符,例如'-',,' | '等。

2.toString()方法

toString()方法将数组转换为字符串,使用逗号分隔元素。



const numbers = [1, 2, 3, 4];
const result = numbers.toString(); // '1,2,3,4'
console.log(result);


Enter fullscreen mode Exit fullscreen mode
  • 语法array.toString()
  • 分隔符:始终使用,(逗号)作为分隔符。

3.String()构造函数

您可以使用String()构造函数将数组转换为字符串。此方法与 类似,toString()但在某些情况下可能更明确。



const boolArray = [true, false, true];
const result = String(boolArray); // 'true,false,true'
console.log(result);


Enter fullscreen mode Exit fullscreen mode
  • 语法String(array)

4.模板字符串

对于自定义格式,您可以使用模板文字将数组转换为字符串。



const colors = ['red', 'green', 'blue'];
const result = `${colors[0]}, ${colors[1]}, ${colors[2]}`; // 'red, green, blue'
console.log(result);


Enter fullscreen mode Exit fullscreen mode
  • 语法:用于${}将数组元素嵌入模板字符串中。

5.Array.prototype.map()join()

为了更好地控制转换,特别是当您需要格式化每个元素时,您可以map()结合使用join()



const numbers = [1, 2, 3];
const result = numbers.map(num => `Number ${num}`).join(' | '); // 'Number 1 | Number 2 | Number 3'
console.log(result);


Enter fullscreen mode Exit fullscreen mode
  • 语法array.map(callback).join(separator)

访问完整阵列



let a = [1, 12, 13, 14, 6, 8,9, 5, 11, 7, 10, 15, 2, 3, 4, 22, 44, 33];
console.log(a);


Enter fullscreen mode Exit fullscreen mode


let a = [1, 12, 13, 14, 6, 8,9, 5, 11, 7, 10, 15, 2, 3, 4, 22, 44, 33];
document.getElementById("demo").innerHTML = a;


Enter fullscreen mode Exit fullscreen mode

在 JavaScript 中,访问数组的全部内容可以通过多种方式实现,具体取决于上下文和目标。以下是访问和使用数组所有元素的几种方法:

1.通过索引直接访问

您可以使用索引直接访问数组中的各个元素。例如,要访问第一个元素,可以使用 index 0



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


Enter fullscreen mode Exit fullscreen mode

2.循环遍历数组

您可以使用循环来遍历数组中的每个元素。以下是一些常见的循环方法:

a.for循环

传统的for循环使您可以控制索引,并且可以用于根据元素的位置修改元素等任务。



const numbers = [10, 20, 30];
for (let i = 0; i < numbers.length; i++) {
  console.log(numbers[i]); // 10, 20, 30
}


Enter fullscreen mode Exit fullscreen mode

b.forEach()方法

forEach()方法对每个数组元素执行一次提供的函数。



const colors = ['red', 'green', 'blue'];
colors.forEach(color => {
  console.log(color); // 'red', 'green', 'blue'
});


Enter fullscreen mode Exit fullscreen mode

c.for...of循环

循环for...of提供了一种更现代、更易读的方式来迭代数组元素。



const fruits = ['apple', 'banana', 'cherry'];
for (const fruit of fruits) {
  console.log(fruit); // 'apple', 'banana', 'cherry'
}


Enter fullscreen mode Exit fullscreen mode

d.map()方法

map()方法通过对每个元素调用提供的函数来创建一个新数组。



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


Enter fullscreen mode Exit fullscreen mode

3.使用数组解构

数组解构允许您将数组中的元素解包到不同的变量中。



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


Enter fullscreen mode Exit fullscreen mode

4.console.log()

要快速查看整个数组,可以使用console.log()



const array = [1, 2, 3, 4, 5];
console.log(array); // [1, 2, 3, 4, 5]


Enter fullscreen mode Exit fullscreen mode

5.toString()方法

将整个数组转换为以逗号分隔的字符串。



const array = [1, 2, 3, 4];
console.log(array.toString()); // '1,2,3,4'


Enter fullscreen mode Exit fullscreen mode

6.join()方法

与 类似toString(),但您可以指定分隔符。



const array = [1, 2, 3, 4];
console.log(array.join(' - ')); // '1 - 2 - 3 - 4'


Enter fullscreen mode Exit fullscreen mode

7.扩展运算符

使用扩展运算符创建一个新数组或将数组元素传递给函数。



const numbers = [1, 2, 3];
const newNumbers = [...numbers];
console.log(newNumbers); // [1, 2, 3]


Enter fullscreen mode Exit fullscreen mode

JavaScript 作为对象



const man = ["Fatema", "CSE", "UU", 24];
console.log(man);


Enter fullscreen mode Exit fullscreen mode

在 JavaScript 中,数组确实是一种对象。这个概念对于理解 JavaScript 中数组的工作原理至关重要。以下将深入探讨为什么数组被视为对象,以及这如何影响其行为:

1.数组作为对象

  • 从对象继承:JavaScript 中的数组继承自Object原型,这意味着它们具有对象的所有属性和方法。这包括诸如hasOwnProperty()toString()等方法。

  • 原型链:数组拥有自己的原型链,它从 扩展而来Array.prototype,而 本身也是一个对象。该原型链为数组提供了其特有的方法,例如push()pop()map()等等。



const arr = [1, 2, 3];
console.log(arr.constructor === Array); // true
console.log(arr instanceof Object); // true
console.log(arr instanceof Array); // true


Enter fullscreen mode Exit fullscreen mode

2.数组特定属性

  • Length 属性:数组具有一个length属性,该属性会随着元素的添加或删除而自动更新。这是数组特有的,在一般对象中不存在。


const fruits = ['apple', 'banana'];
console.log(fruits.length); // 2
fruits.push('cherry');
console.log(fruits.length); // 3


Enter fullscreen mode Exit fullscreen mode
  • 基于索引的访问:数组使用数字索引来访问元素,而对象使用字符串键。这是数组和常规对象之间的关键区别。


const arr = ['a', 'b', 'c'];
console.log(arr[0]); // 'a'


Enter fullscreen mode Exit fullscreen mode

3.数组与对象

  • 可枚举性:数组具有数字索引,通常用于元素顺序很重要的场景。对象使用字符串键,通常用于顺序不太重要的键值对。

  • 原型方法:数组带有一组特定于数组操作的方法,例如concat()slice()reduce()。对象具有来自 的方法和属性Object.prototype,例如hasOwnProperty()



const obj = { a: 1, b: 2 };
console.log(Object.keys(obj)); // ['a', 'b']

const arr = [1, 2, 3];
console.log(arr.map(x => x * 2)); // [2, 4, 6]


Enter fullscreen mode Exit fullscreen mode

4.数组作为对象的实践

  • 附加属性:您可以像对象一样向数组添加自定义属性,尽管这并不常见。这不会影响数组的行为,但在使用数组方法或属性时可能会导致意外结果。


const arr = [1, 2, 3];
arr.customProperty = 'value';
console.log(arr.customProperty); // 'value'


Enter fullscreen mode Exit fullscreen mode
  • 数组方法:诸如forEach()filter()和 等方法map()对数组进行操作,但它们不属于基础Object原型。它们在 上定义Array.prototype


const numbers = [1, 2, 3];
numbers.forEach(num => console.log(num)); // 1 2 3


Enter fullscreen mode Exit fullscreen mode

5.实际意义

  • 用例:当需要存储有序的数据集合并执行涉及序列和基于索引的访问操作时,数组是最佳选择。对象更适合存储具有命名属性且顺序不重要的数据。

  • 性能:由于 JavaScript 引擎对数组的特殊处理,数组可以针对顺序访问和操作进行优化。对象则针对基于键的访问进行了优化。

length 属性

JavaScript 中的属性length是数组和字符串中的特殊属性,它在管理数据集合中起着至关重要的作用。以下是该length属性工作原理的全面概述:

1.length数组中的属性

数组的属性length返回数组中元素的数量。它是一个动态属性,在数组中添加或删除元素时会自动更新。

基本用法



const fruits = ['apple', 'banana', 'cherry'];
console.log(fruits.length); // 3


Enter fullscreen mode Exit fullscreen mode

动态更新

  • 添加元素:当您向数组添加元素时,length属性会增加。


  const numbers = [1, 2, 3];
  numbers.push(4);
  console.log(numbers.length); // 4


Enter fullscreen mode Exit fullscreen mode
  • 删除元素:当您删除元素时,length属性会减少。


  const numbers = [1, 2, 3];
  numbers.pop();
  console.log(numbers.length); // 2


Enter fullscreen mode Exit fullscreen mode
  • 直接设置长度:您也可以length手动设置该属性。这将截断数组或用空槽填充。


  const numbers = [1, 2, 3, 4, 5];
  numbers.length = 3;
  console.log(numbers); // [1, 2, 3]

  numbers.length = 5;
  console.log(numbers); // [1, 2, 3, <2 empty items>]


Enter fullscreen mode Exit fullscreen mode
  • 截断:设置length为较小的数字会将数组截断为该长度。
  • 填充:设置length为较大的数字会undefined向数组中添加空槽(值)。

2.length字符串中的属性

字符串的属性length返回字符串中的字符数。

基本用法



const message = 'Hello, World!';
console.log(message.length); // 13


Enter fullscreen mode Exit fullscreen mode

3. 特殊注意事项

  • 稀疏数组:数组可能是稀疏的,这意味着它们可能存在“空洞”,索引没有明确赋值。该length属性反映的是最高索引加一,而不是实际元素的数量。


  const arr = [1, , 3];
  console.log(arr.length); // 3


Enter fullscreen mode Exit fullscreen mode

这里,arralength为 3,但只有两个索引(02)有值。索引1为“空”,但仍计入长度。

  • 负索引:该length属性不支持负索引。负索引不属于标准 JavaScript 数组索引。

4.实际用途

  • 迭代:了解数组或字符串的长度对于迭代元素至关重要。


  const arr = ['a', 'b', 'c'];
  for (let i = 0; i < arr.length; i++) {
    console.log(arr[i]); // 'a', 'b', 'c'
  }


Enter fullscreen mode Exit fullscreen mode
  • 验证:使用该length属性来验证输入,例如确保用户输入的字符串满足最小长度要求。


  function validatePassword(password) {
    return password.length >= 8;
  }


Enter fullscreen mode Exit fullscreen mode
  • 填充和截断:通过设置属性调整数组和字符串的大小以满足特定要求length


  const arr = [1, 2, 3];
  arr.length = 5; // Adds two empty slots


Enter fullscreen mode Exit fullscreen mode

添加数组元素

在 JavaScript 中,向数组添加元素有多种方法,具体取决于要添加元素的位置以及要如何操作数组。以下详细介绍了向数组添加元素的各种技术:

1. 使用push()

push()方法将一个或多个元素添加到数组的末尾,并返回数组的新长度。



const fruits = ['apple', 'banana'];
fruits.push('cherry'); // Adds 'cherry' to the end
console.log(fruits); // ['apple', 'banana', 'cherry']


Enter fullscreen mode Exit fullscreen mode
  • 语法array.push(element1, element2, ..., elementN)

2. 使用unshift()

unshift()方法将一个或多个元素添加到数组的开头并返回数组的新长度。



const fruits = ['banana', 'cherry'];
fruits.unshift('apple'); // Adds 'apple' to the beginning
console.log(fruits); // ['apple', 'banana', 'cherry']


Enter fullscreen mode Exit fullscreen mode
  • 语法array.unshift(element1, element2, ..., elementN)

3. 使用splice()

splice()方法可以在数组的任意位置添加元素。它也可以用于删除元素。



const fruits = ['apple', 'cherry'];
fruits.splice(1, 0, 'banana'); // At index 1, remove 0 elements, add 'banana'
console.log(fruits); // ['apple', 'banana', 'cherry']


Enter fullscreen mode Exit fullscreen mode
  • 语法array.splice(start, deleteCount, element1, element2, ..., elementN)
    • start:开始添加元素的索引。
    • deleteCount:要删除的元素数量(如果仅添加则为 0)。
    • element1, ..., elementN:要添加的元素。

4. 使用扩展运算符

扩展运算符 ( ...) 允许你将一个数组中的元素添加到另一个数组中。这对于组合数组特别有用。



const fruits = ['apple', 'banana'];
const moreFruits = ['cherry', 'date'];
const allFruits = [...fruits, ...moreFruits];
console.log(allFruits); // ['apple', 'banana', 'cherry', 'date']


Enter fullscreen mode Exit fullscreen mode
  • 语法const newArray = [...array1, ...array2, ...array3]

5. 使用concat()

concat()方法通过组合多个数组或值来创建一个新数组。



const fruits = ['apple', 'banana'];
const moreFruits = ['cherry', 'date'];
const allFruits = fruits.concat(moreFruits);
console.log(allFruits); // ['apple', 'banana', 'cherry', 'date']


Enter fullscreen mode Exit fullscreen mode
  • 语法array1.concat(array2, array3, ..., value1, value2, ...)

6. 使用扩展运算符进行数组解构

您可以使用数组解构和扩展运算符将元素添加到数组中的特定位置。



const fruits = ['apple', 'date'];
const newFruits = ['banana', ...fruits, 'cherry'];
console.log(newFruits); // ['banana', 'apple', 'date', 'cherry']


Enter fullscreen mode Exit fullscreen mode
  • 语法const newArray = [element1, ...oldArray, elementN]

7.插入多个元素

您可以使用splice()在特定索引处插入多个元素。



const numbers = [1, 2, 5];
numbers.splice(2, 0, 3, 4); // Insert 3 and 4 at index 2
console.log(numbers); // [1, 2, 3, 4, 5]


Enter fullscreen mode Exit fullscreen mode

8. 处理空槽

当使用length添加元素时,请注意它将添加空槽。



const arr = [1, 2, 3];
arr.length = 5; // Adds two empty slots
console.log(arr); // [1, 2, 3, <2 empty items>]


Enter fullscreen mode Exit fullscreen mode

嵌套数组和对象

JavaScript 中的嵌套数组和对象是强大的功能,可用于创建复杂的数据结构。它们可用于表示多维数据、层次结构或任何以分层方式组织数据的场景。

1.嵌套数组

嵌套数组是指包含其他数组作为其元素的数组。这在表示矩阵、网格或分层数据时非常有用。

嵌套数组的示例



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

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

// Iterating through a nested array
for (const row of matrix) {
  for (const value of row) {
    console.log(value);
  }
}


Enter fullscreen mode Exit fullscreen mode

2.嵌套对象

嵌套对象是指包含其他对象作为其属性的对象。这对于表示分层数据或具有多个属性的实体非常有用。

嵌套对象的示例



const person = {
  name: 'John Doe',
  age: 30,
  address: {
    street: '123 Main St',
    city: 'Anytown',
    zipCode: '12345'
  },
  hobbies: ['reading', 'gaming']
};

// Accessing nested properties
console.log(person.address.street); // '123 Main St'
console.log(person.hobbies[1]); // 'gaming'

// Iterating through a nested object
for (const key in person) {
  if (typeof person[key] === 'object' && !Array.isArray(person[key])) {
    console.log(`Nested object ${key}:`);
    for (const subKey in person[key]) {
      console.log(`  ${subKey}: ${person[key][subKey]}`);
    }
  } else {
    console.log(`${key}: ${person[key]}`);
  }
}


Enter fullscreen mode Exit fullscreen mode

3. 组合嵌套数组和对象

您可以将数组和对象组合起来,以创建更复杂的结构。例如,您可能有一个对象数组,其中每个对象都包含嵌套数组或其他对象。

组合嵌套数组和对象的示例



const classRoom = [
  {
    name: 'Math',
    students: [
      { name: 'Alice', score: 95 },
      { name: 'Bob', score: 88 }
    ]
  },
  {
    name: 'Science',
    students: [
      { name: 'Charlie', score: 92 },
      { name: 'David', score: 85 }
    ]
  }
];

// Accessing data
console.log(classRoom[0].students[1].name); // 'Bob'
console.log(classRoom[1].students[0].score); // 92

// Iterating through the combined structure
for (const subject of classRoom) {
  console.log(`Subject: ${subject.name}`);
  for (const student of subject.students) {
    console.log(`  Student: ${student.name}, Score: ${student.score}`);
  }
}


Enter fullscreen mode Exit fullscreen mode

4. 操作嵌套结构

  • 访问:对对象使用点符号或括号符号,对数组使用索引。

  • 更新:为嵌套属性或元素分配新值。



  person.address.city = 'New City'; // Update a nested property
  classRoom[0].students[0].score = 97; // Update a nested element


Enter fullscreen mode Exit fullscreen mode
  • 添加:根据需要添加新属性或元素。


  person.phone = '555-5555'; // Add a new property
  classRoom.push({ name: 'History', students: [] }); // Add a new subject


Enter fullscreen mode Exit fullscreen mode
  • 删除delete用于属性和.splice()数组元素。


  delete person.phone; // Remove a nested property
  classRoom[1].students.splice(1, 1); // Remove a student


Enter fullscreen mode Exit fullscreen mode

5.实际用例

  • 数据表示:表示复杂的数据结构,例如配置设置,分层数据(例如组织结构图)和多维数据集。

  • API 和数据库:通常用于 API 响应和数据库查询来表示复杂的记录。

  • 表单数据:用于处理嵌套表单数据,例如包含部分或字段组的表单。

JavaScript 数组方法

JavaScript 数组带有丰富的内置方法,可帮助您操作和与数组数据交互。这些方法大致可分为几类,包括用于修改数组、访问元素以及迭代元素的方法。以下是常见数组方法的全面概述:

1. 添加和删除元素

  • push():将一个或多个元素添加到数组末尾。


  const fruits = ['apple', 'banana'];
  fruits.push('cherry'); // ['apple', 'banana', 'cherry']


Enter fullscreen mode Exit fullscreen mode
  • pop():从数组中删除最后一个元素并返回它。


  const fruits = ['apple', 'banana', 'cherry'];
  const lastFruit = fruits.pop(); // 'cherry'


Enter fullscreen mode Exit fullscreen mode
  • unshift():将一个或多个元素添加到数组的开头。


  const fruits = ['banana', 'cherry'];
  fruits.unshift('apple'); // ['apple', 'banana', 'cherry']


Enter fullscreen mode Exit fullscreen mode
  • shift():从数组中删除第一个元素并返回它。


  const fruits = ['apple', 'banana', 'cherry'];
  const firstFruit = fruits.shift(); // 'apple'


Enter fullscreen mode Exit fullscreen mode
  • splice():从特定索引添加或删除元素。


  const fruits = ['apple', 'banana', 'cherry'];
  fruits.splice(1, 1, 'blueberry'); // ['apple', 'blueberry', 'cherry']


Enter fullscreen mode Exit fullscreen mode
  • 语法array.splice(start, deleteCount, item1, item2, ...)

2. 访问和搜索元素

  • indexOf():返回可以找到给定元素的第一个索引,-1如果未找到则返回该索引。


  const fruits = ['apple', 'banana', 'cherry'];
  const index = fruits.indexOf('banana'); // 1


Enter fullscreen mode Exit fullscreen mode
  • includes():检查数组是否包含特定元素。


  const fruits = ['apple', 'banana', 'cherry'];
  const hasBanana = fruits.includes('banana'); // true


Enter fullscreen mode Exit fullscreen mode
  • find():返回满足提供的测试函数的第一个元素。


  const numbers = [1, 2, 3, 4];
  const firstEven = numbers.find(num => num % 2 === 0); // 2


Enter fullscreen mode Exit fullscreen mode
  • findIndex():返回满足提供的测试函数的第一个元素的索引。


  const numbers = [1, 2, 3, 4];
  const index = numbers.findIndex(num => num % 2 === 0); // 1


Enter fullscreen mode Exit fullscreen mode

3. 迭代元素

  • forEach():对每个数组元素执行一次提供的函数。


  const fruits = ['apple', 'banana', 'cherry'];
  fruits.forEach(fruit => console.log(fruit));


Enter fullscreen mode Exit fullscreen mode
  • map():使用对每个元素调用提供的函数的结果创建一个新数组。


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


Enter fullscreen mode Exit fullscreen mode
  • filter():创建一个新数组,其中包含通过提供的函数实现的测试的所有元素。


  const numbers = [1, 2, 3, 4];
  const evens = numbers.filter(num => num % 2 === 0); // [2, 4]


Enter fullscreen mode Exit fullscreen mode
  • reduce():对累加器和每个元素应用函数以将其减少为单个值。


  const numbers = [1, 2, 3, 4];
  const sum = numbers.reduce((acc, num) => acc + num, 0); // 10


Enter fullscreen mode Exit fullscreen mode
  • reduceRight():类似于reduce(),但从数组的右端开始。


  const numbers = [1, 2, 3, 4];
  const product = numbers.reduceRight((acc, num) => acc * num, 1); // 24


Enter fullscreen mode Exit fullscreen mode
  • some():测试数组中是否至少有一个元素通过提供的函数。


  const numbers = [1, 2, 3, 4];
  const hasEven = numbers.some(num => num % 2 === 0); // true


Enter fullscreen mode Exit fullscreen mode
  • every():测试数组中的所有元素是否都通过提供的函数。


  const numbers = [2, 4, 6];
  const allEven = numbers.every(num => num % 2 === 0); // true


Enter fullscreen mode Exit fullscreen mode

4. 排序和反转

  • sort():对数组元素进行排序并返回该数组。


  const numbers = [4, 2, 3, 1];
  numbers.sort(); // [1, 2, 3, 4]


Enter fullscreen mode Exit fullscreen mode
  • 注意:sort()默认情况下,元素按字符串排序。对于数值排序,请使用比较函数。


  const numbers = [4, 2, 3, 1];
  numbers.sort((a, b) => a - b); // [1, 2, 3, 4]


Enter fullscreen mode Exit fullscreen mode
  • reverse():就地反转数组的元素。


  const numbers = [1, 2, 3];
  numbers.reverse(); // [3, 2, 1]


Enter fullscreen mode Exit fullscreen mode

5.数组转换

  • concat():将两个或多个数组合并为一个新数组。


  const arr1 = [1, 2];
  const arr2 = [3, 4];
  const combined = arr1.concat(arr2); // [1, 2, 3, 4]


Enter fullscreen mode Exit fullscreen mode
  • slice():将数组的一部分的浅拷贝返回到新数组中。


  const numbers = [1, 2, 3, 4];
  const sliced = numbers.slice(1, 3); // [2, 3]


Enter fullscreen mode Exit fullscreen mode
  • splice():通过添加、移除或替换元素来修改数组。(另请参阅“添加/移除元素”部分。)


  const numbers = [1, 2, 3, 4];
  numbers.splice(2, 1, 'a', 'b'); // [1, 2, 'a', 'b', 4]


Enter fullscreen mode Exit fullscreen mode

6.字符串转换

  • toString():将数组转换为字符串,元素以逗号分隔。


  const numbers = [1, 2, 3];
  const str = numbers.toString(); // '1,2,3'


Enter fullscreen mode Exit fullscreen mode
  • join():将数组的所有元素用指定的分隔符连接成一个字符串。


  const numbers = [1, 2, 3];
  const str = numbers.join('-'); // '1-2-3'


Enter fullscreen mode Exit fullscreen mode

JavaScript 数组搜索

JavaScript 数组自带各种用于搜索和定位元素的方法。这些方法可用于查找特定值、检查元素是否存在或检索索引。以下是主要数组搜索方法的详细概述:

1.indexOf()

indexOf()方法返回可以找到给定元素的第一个索引,或者-1返回未找到该元素的第一个索引。



const fruits = ['apple', 'banana', 'cherry'];
const index = fruits.indexOf('banana'); // 1
const notFound = fruits.indexOf('orange'); // -1


Enter fullscreen mode Exit fullscreen mode
  • 语法array.indexOf(searchElement, fromIndex)

    • searchElement:要搜索的元素。
    • fromIndex(可选):开始搜索的索引。

2.includes()

includes()方法确定数组是否包含某个元素并返回truefalse



const fruits = ['apple', 'banana', 'cherry'];
const hasBanana = fruits.includes('banana'); // true
const hasOrange = fruits.includes('orange'); // false


Enter fullscreen mode Exit fullscreen mode
  • 语法array.includes(searchElement, fromIndex)

    • searchElement:要搜索的元素。
    • fromIndex(可选):开始搜索的索引。

3.find()

find()方法返回数组中第一个满足所提供测试函数的元素。如果没有元素满足测试函数,则返回undefined



const numbers = [4, 9, 16, 25];
const firstEven = numbers.find(num => num % 2 === 0); // 4
const noMatch = numbers.find(num => num > 30); // undefined


Enter fullscreen mode Exit fullscreen mode
  • 语法array.find(callback(element, index, array), thisArg)

    • callback:测试每个元素的函数。
    • thisArg(可选):this执行时要使用的值callback

4.findIndex()

findIndex()方法返回数组中第一个满足指定测试函数的元素的索引。如果没有元素满足测试函数,则返回-1



const numbers = [4, 9, 16, 25];
const index = numbers.findIndex(num => num % 2 === 0); // 0
const noMatchIndex = numbers.findIndex(num => num > 30); // -1


Enter fullscreen mode Exit fullscreen mode
  • 语法array.findIndex(callback(element, index, array), thisArg)

    • callback:测试每个元素的函数。
    • thisArg(可选):this执行时要使用的值callback

5.some()

some()方法测试数组中是否至少有一个元素通过了提供的测试函数。true如果任何元素通过测试,则返回 ,否则返回false



const numbers = [1, 2, 3, 4];
const hasEven = numbers.some(num => num % 2 === 0); // true
const allEven = numbers.some(num => num % 2 === 0 && num > 5); // false


Enter fullscreen mode Exit fullscreen mode
  • 语法array.some(callback(element, index, array), thisArg)

    • callback:测试每个元素的函数。
    • thisArg(可选):this执行时要使用的值callback

6.every()

every()方法测试数组中的所有元素是否都通过了提供的测试函数。true如果所有元素都通过测试,则返回 ,否则返回false



const numbers = [2, 4, 6];
const allEven = numbers.every(num => num % 2 === 0); // true
const notAllEven = numbers.every(num => num > 3); // false


Enter fullscreen mode Exit fullscreen mode
  • 语法array.every(callback(element, index, array), thisArg)

    • callback:测试每个元素的函数。
    • thisArg(可选):this执行时要使用的值callback

7.filter()

filter()方法创建一个新数组,其中包含通过所提供函数实现的测试的所有元素。



const numbers = [1, 2, 3, 4, 5];
const evens = numbers.filter(num => num % 2 === 0); // [2, 4]


Enter fullscreen mode Exit fullscreen mode
  • 语法array.filter(callback(element, index, array), thisArg)

    • callback:测试每个元素的函数。
    • thisArg(可选):this执行时要使用的值callback

8.findLast()(实验)

findLast()方法返回数组中满足所提供测试函数的最后一个元素。如果没有元素满足测试函数,则返回undefined。请注意,此方法尚处于实验阶段,可能并非所有环境都支持。



const numbers = [4, 9, 16, 25];
const lastEven = numbers.findLast(num => num % 2 === 0); // 16


Enter fullscreen mode Exit fullscreen mode
  • 语法array.findLast(callback(element, index, array), thisArg)

    • callback:测试每个元素的函数。
    • thisArg(可选):this执行时要使用的值callback

9.findLastIndex()(实验)

findLastIndex()方法返回数组中最后一个满足指定测试函数的元素的索引。如果没有元素满足测试函数,则返回-1。请注意,此方法尚处于实验阶段,可能并非所有环境都支持。



const numbers = [4, 9, 16, 25];
const lastEvenIndex = numbers.findLastIndex(num => num % 2 === 0); // 2


Enter fullscreen mode Exit fullscreen mode
  • 语法array.findLastIndex(callback(element, index, array), thisArg)

    • callback:测试每个元素的函数。
    • thisArg(可选):this执行时要使用的值callback

JavaScript 数组排序

在 JavaScript 中,可以使用该sort()方法对数组进行排序。此方法允许您按照指定的顺序排列数组中的元素。默认情况下,该sort()方法将元素按字符串排序,但您可以提供自定义比较函数,以不同的方式对元素进行排序。

基本用法sort()

sort()方法对数组元素进行排序返回排序后的数组。



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


Enter fullscreen mode Exit fullscreen mode

使用比较函数进行自定义排序

要按特定顺序对元素进行排序,需要将比较函数传递给sort()。比较函数接受两个参数(我们分别称为ab)并返回:

  • 负值 ifa应该位于 之前b
  • 如果ab在排序顺序中相等,则为零。
  • 正值 ifa应该在 之后b

数字排序

默认情况下,该sort()方法会将数字转换为字符串,并按字典顺序排序。为了正确排序数字,请提供一个执行数值比较的比较函数。



const numbers = [10, 5, 100, 1];
numbers.sort((a, b) => a - b); // Ascending order
console.log(numbers); // [1, 5, 10, 100]

numbers.sort((a, b) => b - a); // Descending order
console.log(numbers); // [100, 10, 5, 1]


Enter fullscreen mode Exit fullscreen mode

字符串排序

字符串默认按字典顺序排序。如果需要不区分大小写,可以在比较函数中将字符串转换为大小写相同的字符串(例如小写)。



const words = ['banana', 'Apple', 'cherry'];
words.sort((a, b) => a.localeCompare(b)); // Case-sensitive
console.log(words); // ['Apple', 'banana', 'cherry']

words.sort((a, b) => a.toLowerCase().localeCompare(b.toLowerCase())); // Case-insensitive
console.log(words); // ['Apple', 'banana', 'cherry']


Enter fullscreen mode Exit fullscreen mode

排序对象

要对对象数组进行排序,请使用比较函数来比较对象的所需属性。



const people = [
  { name: 'John', age: 30 },
  { name: 'Jane', age: 25 },
  { name: 'Mike', age: 35 }
];

// Sort by age
people.sort((a, b) => a.age - b.age);
console.log(people);
// [ { name: 'Jane', age: 25 }, { name: 'John', age: 30 }, { name: 'Mike', age: 35 } ]

// Sort by name
people.sort((a, b) => a.name.localeCompare(b.name));
console.log(people);
// [ { name: 'Jane', age: 25 }, { name: 'John', age: 30 }, { name: 'Mike', age: 35 } ]


Enter fullscreen mode Exit fullscreen mode

对多维数组进行排序

对多维数组(数组的数组)进行排序时,提供比较相关元素的比较函数。



const matrix = [
  [1, 4],
  [3, 2],
  [5, 0]
];

// Sort by the first element of each sub-array
matrix.sort((a, b) => a[0] - b[0]);
console.log(matrix); // [ [1, 4], [3, 2], [5, 0] ]

// Sort by the second element of each sub-array
matrix.sort((a, b) => a[1] - b[1]);
console.log(matrix); // [ [5, 0], [3, 2], [1, 4] ]


Enter fullscreen mode Exit fullscreen mode

稳定排序

JavaScript 的sort()方法在现代环境中是稳定的,这意味着具有相等值的元素会保留其相对顺序。但是,并非所有 JavaScript 引擎都能保证这一点,因此如果稳定性至关重要,请考虑使用自定义的稳定排序算法或库。

排序localeCompare()

localeCompare()方法可用于以区域感知的方式对字符串进行排序,以适应不同的文化排序规则。



const words = ['résumé', 'resume', 'apple'];
words.sort((a, b) => a.localeCompare(b, 'en', { sensitivity: 'base' }));
console.log(words); // ['apple', 'resume', 'résumé']


Enter fullscreen mode Exit fullscreen mode

JavaScript 数组迭代

JavaScript 提供了多种数组迭代方法,允许你对每个元素执行函数,或以各种方式转换数组。以下是 JavaScript 中可用的数组迭代方法的全面概述:

1.forEach()

forEach()方法对每个数组元素执行一次提供的函数。它不返回任何值,也无法停止或提前中断。



const fruits = ['apple', 'banana', 'cherry'];
fruits.forEach(fruit => console.log(fruit));
// Output:
// apple
// banana
// cherry


Enter fullscreen mode Exit fullscreen mode
  • 语法array.forEach(callback(element, index, array), thisArg)

    • callback:针对每个元素执行的函数。
    • thisArg(可选):this执行时要使用的值callback

2.map()

map()方法通过对原始数组中的每个元素调用提供的函数来创建一个新数组。它用于转换元素。



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


Enter fullscreen mode Exit fullscreen mode
  • 语法array.map(callback(element, index, array), thisArg)

    • callback:针对每个元素执行的函数。
    • thisArg(可选):this执行时要使用的值callback

3.filter()

filter()方法创建一个新数组,其中包含所有通过所提供函数测试的元素。它用于选择符合特定条件的元素。



const numbers = [1, 2, 3, 4, 5];
const evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // [2, 4]


Enter fullscreen mode Exit fullscreen mode
  • 语法array.filter(callback(element, index, array), thisArg)

    • callback:针对每个元素执行的函数。
    • thisArg(可选):this执行时要使用的值callback

4.reduce()

reduce()方法对累加器和数组中的每个元素应用一个函数,以将其减少为单个值,例如总和或连接的字符串。



const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 10


Enter fullscreen mode Exit fullscreen mode
  • 语法array.reduce(callback(accumulator, currentValue, index, array), initialValue)

    • callback:针对每个元素执行的函数。
    • initialValue(可选):用作第一次调用的第一个参数的值callback

5.reduceRight()

reduceRight()方法与类似reduce(),但它从右到左处理数组。



const numbers = [1, 2, 3, 4];
const product = numbers.reduceRight((acc, num) => acc * num, 1);
console.log(product); // 24


Enter fullscreen mode Exit fullscreen mode
  • 语法array.reduceRight(callback(accumulator, currentValue, index, array), initialValue)

    • callback:针对每个元素执行的函数。
    • initialValue(可选):用作第一次调用的第一个参数的值callback

6.some()

some()方法测试数组中是否至少有一个元素通过了所提供函数实现的测试。true如果至少有一个元素通过测试,则返回 ,否则返回false



const numbers = [1, 2, 3, 4];
const hasEven = numbers.some(num => num % 2 === 0);
console.log(hasEven); // true


Enter fullscreen mode Exit fullscreen mode
  • 语法array.some(callback(element, index, array), thisArg)

    • callback:针对每个元素执行的函数。
    • thisArg(可选):this执行时要使用的值callback

7.every()

every()方法测试数组中的所有元素是否都通过了所提供函数实现的测试。true如果所有元素都通过测试,则返回 ,否则返回false



const numbers = [2, 4, 6];
const allEven = numbers.every(num => num % 2 === 0);
console.log(allEven); // true


Enter fullscreen mode Exit fullscreen mode
  • 语法array.every(callback(element, index, array), thisArg)

    • callback:针对每个元素执行的函数。
    • thisArg(可选):this执行时要使用的值callback

8.find()

find()方法返回数组中第一个满足所提供测试函数的元素。如果没有元素满足测试函数,则返回undefined



const numbers = [4, 9, 16, 25];
const firstEven = numbers.find(num => num % 2 === 0);
console.log(firstEven); // 4


Enter fullscreen mode Exit fullscreen mode
  • 语法array.find(callback(element, index, array), thisArg)

    • callback:针对每个元素执行的函数。
    • thisArg(可选):this执行时要使用的值callback

9.findIndex()

findIndex()方法返回数组中第一个满足所提供测试函数的元素的索引。如果没有元素满足测试函数,则返回-1



const numbers = [4, 9, 16, 25];
const index = numbers.findIndex(num => num % 2 === 0);
console.log(index); // 0


Enter fullscreen mode Exit fullscreen mode
  • 语法array.findIndex(callback(element, index, array), thisArg)

    • callback:针对每个元素执行的函数。
    • thisArg(可选):this执行时要使用的值callback

10.for...of循环

循环for...of提供了一种简洁的语法来迭代可迭代对象(例如数组)。它对于循环遍历数组值尤其有用。



const fruits = ['apple', 'banana', 'cherry'];
for (const fruit of fruits) {
  console.log(fruit);
}
// Output:
// apple
// banana
// cherry


Enter fullscreen mode Exit fullscreen mode

11.for...in循环

for...in循环会迭代对象的可枚举属性。当用于数组时,它会迭代数组索引,而不是值。通常不建议将其用于数组,因为它是为对象设计的。



const fruits = ['apple', 'banana', 'cherry'];
for (const index in fruits) {
  console.log(index); // 0, 1, 2
}


Enter fullscreen mode Exit fullscreen mode

12.flatMap()

flatMap()方法首先使用映射函数映射每个元素,然后将结果展平为一个新数组。当你需要一次性映射并展平结果时,这种方法非常有用。



const numbers = [1, 2, 3];
const flattened = numbers.flatMap(num => [num, num * 2]);
console.log(flattened); // [1, 2, 2, 4, 3, 6]


Enter fullscreen mode Exit fullscreen mode
  • 语法array.flatMap(callback(element, index, array), thisArg)

    • callback:针对每个元素执行的函数。
    • thisArg(可选):this执行时要使用的值callback

JavaScript 数组常量

在 JavaScript 中,const是一个关键字,用于声明那些需要保持常量的变量——即它们的引用不能被重新赋值。然而,这并不意味着它们指向的值或对象是不可变的。对于使用 声明的数组const,数组本身不能被重新赋值,但其元素仍然可以被修改。

const以下是使用数组的更详细的介绍:

1. 使用以下方式声明数组const

使用 声明数组时const,实际上是在创建对该数组的常量引用。这意味着您无法将数组重新赋值给其他值或数组,但仍然可以修改其元素或结构(例如添加或删除元素)。



const fruits = ['apple', 'banana', 'cherry'];

// Valid: modifying elements
fruits[0] = 'blueberry'; // ['blueberry', 'banana', 'cherry']
fruits.push('date');     // ['blueberry', 'banana', 'cherry', 'date']

console.log(fruits);

// Invalid: reassigning the array
fruits = ['kiwi', 'mango']; // TypeError: Assignment to constant variable.


Enter fullscreen mode Exit fullscreen mode

2.修改数组

尽管您无法重新分配const数组,但您可以使用数组方法来修改其内容:

  • 添加元素:使用诸如push()unshift()或之类的方法splice()


  const numbers = [1, 2, 3];
  numbers.push(4); // [1, 2, 3, 4]
  numbers.unshift(0); // [0, 1, 2, 3, 4]


Enter fullscreen mode Exit fullscreen mode
  • 删除元素:使用诸如pop()shift()或之类的方法splice()


  const colors = ['red', 'green', 'blue'];
  colors.pop(); // ['red', 'green']
  colors.shift(); // ['green']


Enter fullscreen mode Exit fullscreen mode
  • 修改元素:通过索引直接访问和更改元素。


  const animals = ['cat', 'dog', 'bird'];
  animals[1] = 'fish'; // ['cat', 'fish', 'bird']


Enter fullscreen mode Exit fullscreen mode

3. 数组方法

允许使用以下方法来修改数组:

  • sort():对数组元素进行排序。```javascript

const numbers = [3, 1, 4, 1, 5];
numbers.sort(); // [1, 1, 3, 4, 5]


- **`reverse()`**: Reverses the order of elements.
  ```javascript


  const letters = ['a', 'b', 'c'];
  letters.reverse(); // ['c', 'b', 'a']


Enter fullscreen mode Exit fullscreen mode
  • splice():添加或删除元素。```javascript

const fruit = ['apple', 'banana', 'cherry'];
fruit.splice(1, 1, 'blueberry', 'date'); // ['apple', 'blueberry', 'date', 'cherry']


4. Immutability of Arrays

If you need an immutable array, where changes to the array are not allowed, you need to use additional techniques or libraries to achieve this. JavaScript itself does not provide immutable arrays directly.

For example, you could use libraries like Immutable.js for immutability:



import { List } from 'immutable';

const immutableList = List([1, 2, 3]);
const newList = immutableList.push(4); // Returns a new List: List [ 1, 2, 3, 4 ]
console.log(immutableList); // List [ 1, 2, 3 ]


</code></pre></div><h2>
  <a name="summary" href="#summary">
  </a>
  Summary
</h2>

<p>JavaScript provides a wide range of operations and methods to handle arrays, including creation, manipulation, searching, and iteration. Here's a summary of the most common array operations:</p>
<h3>
  <a name="1-creation-and-initialization" href="#1-creation-and-initialization">
  </a>
  1. <strong>Creation and Initialization</strong>
</h3>

<ul>
<li>
<strong>Literal Syntax</strong>: <code>const array = [1, 2, 3];</code></li>
<li>
<strong>Using <code>Array</code> Constructor</strong>: <code>const array = new Array(3); // Creates an array with 3 empty slots</code></li>
</ul>
<h3>
  <a name="2-accessing-and-modifying-elements" href="#2-accessing-and-modifying-elements">
  </a>
  2. <strong>Accessing and Modifying Elements</strong>
</h3>

<ul>
<li>
<strong>Access by Index</strong>: <code>const firstElement = array[0];</code></li>
<li>
<strong>Modify by Index</strong>: <code>array[0] = 10;</code></li>
</ul>
<h3>
  <a name="3-array-methods" href="#3-array-methods">
  </a>
  3. <strong>Array Methods</strong>
</h3>
<h4>
  <a name="creation-and-transformation" href="#creation-and-transformation">
  </a>
  <strong>Creation and Transformation</strong>
</h4>

<ul>
<li>
<strong><code>concat()</code></strong>: Combines arrays. <code>const combined = array1.concat(array2);</code></li>
<li>
<strong><code>flat()</code></strong>: Flattens nested arrays. <code>const flatArray = nestedArray.flat();</code></li>
<li>
<strong><code>flatMap()</code></strong>: Maps and then flattens. <code>const result = array.flatMap(x =&gt; [x, x * 2]);</code></li>
</ul>
<h4>
  <a name="sorting" href="#sorting">
  </a>
  <strong>Sorting</strong>
</h4>

<ul>
<li>
<strong><code>sort()</code></strong>: Sorts elements. <code>array.sort((a, b) =&gt; a - b);</code></li>
<li>
<strong><code>reverse()</code></strong>: Reverses the order. <code>array.reverse();</code></li>
</ul>
<h4>
  <a name="adding-and-removing-elements" href="#adding-and-removing-elements">
  </a>
  <strong>Adding and Removing Elements</strong>
</h4>

<ul>
<li>
<strong><code>push()</code></strong>: Adds elements to the end. <code>array.push(4);</code></li>
<li>
<strong><code>pop()</code></strong>: Removes the last element. <code>const last = array.pop();</code></li>
<li>
<strong><code>unshift()</code></strong>: Adds elements to the beginning. <code>array.unshift(0);</code></li>
<li>
<strong><code>shift()</code></strong>: Removes the first element. <code>const first = array.shift();</code></li>
<li>
<strong><code>splice()</code></strong>: Adds or removes elements at a specified index. <code>array.splice(1, 1, 'newElement');</code></li>
</ul>
<h4>
  <a name="iteration" href="#iteration">
  </a>
  <strong>Iteration</strong>
</h4>

<ul>
<li>
<strong><code>forEach()</code></strong>: Executes a function on each element. <code>array.forEach(element =&gt; console.log(element));</code></li>
<li>
<strong><code>map()</code></strong>: Transforms elements and returns a new array. <code>const newArray = array.map(x =&gt; x * 2);</code></li>
<li>
<strong><code>filter()</code></strong>: Returns elements that pass a test. <code>const filtered = array.filter(x =&gt; x % 2 === 0);</code></li>
<li>
<strong><code>reduce()</code></strong>: Reduces array to a single value. <code>const sum = array.reduce((acc, x) =&gt; acc + x, 0);</code></li>
<li>
<strong><code>reduceRight()</code></strong>: Reduces array from right to left. <code>const product = array.reduceRight((acc, x) =&gt; acc * x, 1);</code></li>
<li>
<strong><code>some()</code></strong>: Tests if any elements pass a test. <code>const hasEven = array.some(x =&gt; x % 2 === 0);</code></li>
<li>
<strong><code>every()</code></strong>: Tests if all elements pass a test. <code>const allPositive = array.every(x =&gt; x &gt; 0);</code></li>
<li>
<strong><code>find()</code></strong>: Finds the first element that passes a test. <code>const found = array.find(x =&gt; x &gt; 3);</code></li>
<li>
<strong><code>findIndex()</code></strong>: Finds the index of the first element that passes a test. <code>const index = array.findIndex(x =&gt; x &gt; 3);</code></li>
<li>
<strong><code>flatMap()</code></strong>: Maps and flattens results. <code>const flattened = array.flatMap(x =&gt; [x, x * 2]);</code></li>
</ul>
<h3>
  <a name="4-search-and-indexing" href="#4-search-and-indexing">
  </a>
  4. <strong>Search and Indexing</strong>
</h3>

<ul>
<li>
<strong><code>indexOf()</code></strong>: Finds the first index of an element. <code>const index = array.indexOf(3);</code></li>
<li>
<strong><code>includes()</code></strong>: Checks if an element exists. <code>const exists = array.includes(3);</code></li>
<li>
<strong><code>lastIndexOf()</code></strong>: Finds the last index of an element. <code>const lastIndex = array.lastIndexOf(3);</code></li>
</ul>
<h3>
  <a name="5-miscellaneous" href="#5-miscellaneous">
  </a>
  5. <strong>Miscellaneous</strong>
</h3>

<ul>
<li>
<strong><code>slice()</code></strong>: Returns a shallow copy of a portion of an array. <code>const subArray = array.slice(1, 3);</code></li>
<li>
<strong><code>join()</code></strong>: Joins array elements into a string. <code>const str = array.join('-');</code></li>
<li>
<strong><code>toString()</code></strong>: Converts array to a string. <code>const str = array.toString();</code></li>
</ul>
<h3>
  <a name="6-array-and-raw-const-endraw-" href="#6-array-and-raw-const-endraw-">
  </a>
  6. <strong>Array and <code>const</code></strong>
</h3>

<ul>
<li>
<strong><code>const</code> with Arrays</strong>: Prevents reassignment of the array reference, but allows modification of array elements and structure. <code>const array = [1, 2, 3]; array.push(4); // Allowed</code></li>
</ul>
<h3>
  <a name="7-advanced-iteration" href="#7-advanced-iteration">
  </a>
  7. <strong>Advanced Iteration</strong>
</h3>

<ul>
<li>
<strong><code>for...of</code></strong>: Iterates over values. <code>for (const value of array) { console.log(value); }</code></li>
<li>
<strong><code>for...in</code></strong>: Iterates over indices (less recommended for arrays). <code>for (const index in array) { console.log(index); }</code></li>
</ul>
<h2>
  <a name="in-short" href="#in-short">
  </a>
  In short
</h2>

<ul>
<li>
<strong>Creation</strong>: Use array literals or constructors.</li>
<li>
<strong>Access/Modify</strong>: Use index-based operations.</li>
<li>
<strong>Methods</strong>: For transformation, sorting, adding/removing, and iteration.</li>
<li>
<strong>Search/Index</strong>: For locating elements and indices.</li>
<li>
<strong><code>const</code></strong>: Use for constant references, allowing modification.</li>
<li>
<strong>Iteration</strong>: Employ <code>forEach()</code>, <code>map()</code>, <code>filter()</code>, etc., for different iteration needs.</li>
</ul>

<p>Understanding and utilizing these operations effectively will help you manage and manipulate arrays in JavaScript with greater efficiency and flexibility.</p>
Enter fullscreen mode Exit fullscreen mode
Enter fullscreen mode Exit fullscreen mode
文章来源:https://dev.to/engrsakib/mastering-javascript-arrays-techniques-best-practices-and-advanced-uses-42mb
PREV
回顾我从新手到中级开发人员的 15 年历程
NEXT
使用 CSS 变量进行主题化。