当前位置:   article > 正文

JS中Array数组方法(秒懂数组方法如何使用)_js array

js array

目录

一、Array数组介绍

1.概念

2.创建数组: 使用数组字面量([])或Array构造函数来创建数组。

3.访问数组元素: 可以使用索引来访问数组中的元素,索引从0开始计数。

4.数组长度: 可以使用length属性获取数组的长度。 

5.JavaScript提供了丰富的数组方法用于操作数组

6.多维数组: JavaScript中的数组也可以是多维的,可以包含其他数组作为其元素。

 7.迭代数组: 可以使用for循环、forEach、map等方法来迭代数组元素。

8.数组的特性

二、Array数组方法实现

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

pop(): 移除数组中的最后一个元素,并返回移除的元素。

shift(): 移除数组中的第一个元素,并返回移除的元素。

 unshift(): 向数组开头添加一个或多个元素,并返回新的长度。

splice(): 从指定位置开始,删除指定数量的元素,并可以在该位置插入新的元素。

 slice(): 返回一个从指定开始索引到结束索引(不包括结束索引)的新数组,原数组不会改变。

 concat(): 将两个或多个数组合并成一个新数组,并返回该新数组。

 forEach(): 遍历数组中的每个元素,并对每个元素执行提供的回调函数。

copyWithin(): 在数组内部将一部分元素拷贝到另一部分元素,不会改变数组长度。

entries(): 返回一个包含数组键值对的迭代器对象。

every(): 判断数组中的所有元素是否满足指定条件。

fill(): 用一个固定值填充数组的所有元素。

filter(): 根据指定函数过滤数组中的元素。

find(): 返回数组中满足提供的测试函数的第一个元素的值。

findIndex(): 返回数组中满足提供的测试函数的第一个元素的索引。

flat(): 将多维数组扁平化为一维数组。

flatMap(): 对数组的每个元素执行指定的函数(类似于map),然后对结果进行扁平化处理,并返回一个新数组。

includes(): 判断数组是否包含指定元素。

indexOf(): 返回指定元素在数组中第一次出现的位置,如果不存在则返回-1。

join(): 将数组中所有元素以指定的分隔符连接成一个字符串。

keys(): 返回一个包含数组索引的迭代器对象。

lastIndexOf(): 返回指定元素在数组中最后一次出现的位置,如果不存在则返回-1。

map(): 对数组中的每个元素执行指定的函数,并返回一个新数组。

reduce(): 对数组中的每个元素执行指定的累积函数,将结果汇总为单个值。

reduceRight(): 类似于reduce()方法,但是从数组的末尾开始。

reverse(): 反转数组中元素的顺序。

some(): 判断数组中是否至少有一个元素满足指定条件。

sort(): 对数组进行排序,可以指定排序规则的比较函数。

toLocaleString(): 返回数组的本地化字符串表示。

toString(): 将数组转换为字符串。

values(): 返回一个包含数组值的迭代器对象。

三、数组应用实例

1.存储和处理数据:

2. 数据可视化:

3. 表单数据处理:

4. 游戏开发:

5.简单的待办事项列表应用程序(完整例子)

四、数组应用场景


一、Array数组介绍

1.概念

JavaScript中的Array(数组)是一种用于存储多个值的数据结构,它是一种有序的集合,可以包含各种类型的数据,例如数字、字符串、对象等。

2.创建数组: 使用数组字面量([])或Array构造函数来创建数组。

  1. const array1 = [1, 2, 3, 4]; // 使用数组字面量创建数组
  2. const array2 = new Array(1, 2, 3, 4); // 使用Array构造函数创建数组

3.访问数组元素: 可以使用索引来访问数组中的元素,索引从0开始计数。

console.log(array1[0]); // 输出:1

4.数组长度: 可以使用length属性获取数组的长度。 

console.log(array1.length); // 输出:4

5.JavaScript提供了丰富的数组方法用于操作数组

例如push、pop、shift、unshift、slice、splice等。具体请看方法实现。

6.多维数组: JavaScript中的数组也可以是多维的,可以包含其他数组作为其元素。

  1. const multiDimArray = [[1, 2], [3, 4], [5, 6]];
  2. console.log(multiDimArray[0][1]); // 输出:2

 7.迭代数组: 可以使用for循环、forEach、map等方法来迭代数组元素。

  1. const array = [1, 2, 3];
  2. for (let i = 0; i < array.length; i++) {
  3. console.log(array[i]);
  4. }
  5. array.forEach(element => console.log(element));
  6. const newArray = array.map(x => x * 2);

8.数组的特性

  • 数组是可变的,可以动态添加、删除、修改元素。
  • 数组中的元素可以是不同类型的数据。
  • 数组可以通过索引访问元素,也可以通过方法进行操作。

二、Array数组方法实现

push(): 向数组末尾添加一个或多个元素,并返回新的长度。
  1. let arr = [1, 2, 3];
  2. arr.push(4);
  3. console.log(arr); // [1, 2, 3, 4]
pop(): 移除数组中的最后一个元素,并返回移除的元素。
  1. let arr = [1, 2, 3];
  2. let removedElement = arr.pop();
  3. console.log(removedElement); // 3
  4. console.log(arr); // [1, 2]
shift(): 移除数组中的第一个元素,并返回移除的元素。
  1. let arr = [1, 2, 3];
  2. let removedElement = arr.shift();
  3. console.log(removedElement); // 1
  4. console.log(arr); // [2, 3]
 unshift(): 向数组开头添加一个或多个元素,并返回新的长度。
  1. let arr = [2, 3];
  2. arr.unshift(1);
  3. console.log(arr); // [1, 2, 3]
splice(): 从指定位置开始,删除指定数量的元素,并可以在该位置插入新的元素。
  1. let arr = [1, 2, 3, 4, 5];
  2. arr.splice(2, 2, 'a', 'b');
  3. console.log(arr); // [1, 2, "a", "b", 5]
 slice(): 返回一个从指定开始索引到结束索引(不包括结束索引)的新数组,原数组不会改变。
  1. let arr = [1, 2, 3, 4, 5];
  2. let newArr = arr.slice(1, 4);
  3. console.log(newArr); // [2, 3, 4]
 concat(): 将两个或多个数组合并成一个新数组,并返回该新数组。
  1. let arr1 = [1, 2];
  2. let arr2 = [3, 4];
  3. let newArr = arr1.concat(arr2);
  4. console.log(newArr); // [1, 2, 3, 4]
 forEach(): 遍历数组中的每个元素,并对每个元素执行提供的回调函数。
  1. let arr = [1, 2, 3];
  2. arr.forEach(function(element) {
  3. console.log(element);
  4. });
  5. // 输出:
  6. // 1
  7. // 2
  8. // 3
copyWithin(): 在数组内部将一部分元素拷贝到另一部分元素,不会改变数组长度。
  1. const array = ['a', 'b', 'c', 'd', 'e'];
  2. console.log(array.copyWithin(0, 3, 4)); // ['d', 'b', 'c', 'd', 'e']
entries(): 返回一个包含数组键值对的迭代器对象。
  1. const array = ['a', 'b', 'c'];
  2. const iterator = array.entries();
  3. for (let [index, element] of iterator) {
  4. console.log(index, element); // 0 'a', 1 'b', 2 'c'
  5. }
every(): 判断数组中的所有元素是否满足指定条件。
  1. const array = [1, 30, 39, 29, 10, 13];
  2. const isBelowThreshold = (currentValue) => currentValue < 40;
  3. console.log(array.every(isBelowThreshold)); // true
fill(): 用一个固定值填充数组的所有元素。
  1. const array = [1, 2, 3, 4];
  2. console.log(array.fill(0, 2, 4)); // [1, 2, 0, 0]
filter(): 根据指定函数过滤数组中的元素。
  1. const array = [12, 5, 8, 130, 44];
  2. const filteredArray = array.filter(element => element >= 10);
  3. console.log(filteredArray); // [12, 130, 44]
find(): 返回数组中满足提供的测试函数的第一个元素的值。
  1. const array = [5, 12, 8, 130, 44];
  2. const found = array.find(element => element > 10);
  3. console.log(found); // 12
findIndex(): 返回数组中满足提供的测试函数的第一个元素的索引。
  1. const array = [5, 12, 8, 130, 44];
  2. const foundIndex = array.findIndex(element => element > 10);
  3. console.log(foundIndex); // 1
flat(): 将多维数组扁平化为一维数组。
  1. const array = [1, 2, [3, 4]];
  2. console.log(array.flat()); // [1, 2, 3, 4]
flatMap(): 对数组的每个元素执行指定的函数(类似于map),然后对结果进行扁平化处理,并返回一个新数组。
  1. const array = [1, 2, 3, 4];
  2. const newArray = array.flatMap(x => [x * 2]);
  3. console.log(newArray); // [2, 4, 6, 8]
includes(): 判断数组是否包含指定元素。
  1. const array = [1, 2, 3];
  2. console.log(array.includes(2)); // true
indexOf(): 返回指定元素在数组中第一次出现的位置,如果不存在则返回-1。
  1. const array = [2, 9, 9];
  2. console.log(array.indexOf(9)); // 1
join(): 将数组中所有元素以指定的分隔符连接成一个字符串。
  1. const array = ['Wind', 'Rain', 'Fire'];
  2. console.log(array.join()); // 'Wind,Rain,Fire'
keys(): 返回一个包含数组索引的迭代器对象。
  1. const array = ['a', 'b', 'c'];
  2. const iterator = array.keys();
  3. for (const key of iterator) {
  4. console.log(key); // 0, 1, 2
  5. }
lastIndexOf(): 返回指定元素在数组中最后一次出现的位置,如果不存在则返回-1。
  1. const array = [2, 5, 9, 2];
  2. console.log(array.lastIndexOf(2)); // 3
map(): 对数组中的每个元素执行指定的函数,并返回一个新数组。
  1. const array = [1, 4, 9, 16];
  2. const newArray = array.map(x => x * 2);
  3. console.log(newArray); // [2, 8, 18, 32]
reduce(): 对数组中的每个元素执行指定的累积函数,将结果汇总为单个值。
  1. const array = [1, 2, 3, 4];
  2. const reducer = (accumulator, currentValue) => accumulator + currentValue;
  3. console.log(array.reduce(reducer)); // 10
reduceRight(): 类似于reduce()方法,但是从数组的末尾开始。
  1. const array = [1, 2, 3, 4];
  2. const reducer = (accumulator, currentValue) => accumulator - currentValue;
  3. console.log(array.reduceRight(reducer)); // -2
reverse(): 反转数组中元素的顺序。
  1. const array = [1, 2, 3];
  2. console.log(array.reverse()); // [3, 2, 1]
some(): 判断数组中是否至少有一个元素满足指定条件。
  1. const array = [1, 2, 3, 4, 5];
  2. const even = (element) => element % 2 === 0;
  3. console.log(array.some(even)); // true
sort(): 对数组进行排序,可以指定排序规则的比较函数。
  1. const array = [3, 1, 4, 1, 5, 9, 2, 6];
  2. console.log(array.sort()); // [1, 1, 2, 3, 4, 5, 6, 9]
toLocaleString(): 返回数组的本地化字符串表示。
  1. const array = [1, 'a', new Date('21 Dec 1997 14:12:00 UTC')];
  2. console.log(array.toLocaleString('en', { timeZone: 'UTC' }));
  3. // '1,a,12/21/1997, 2:12:00 PM'
toString(): 将数组转换为字符串。
  1. const array = [1, 2, 'a', 'b'];
  2. console.log(array.toString()); // '1,2,a,b'
values(): 返回一个包含数组值的迭代器对象。
  1. const array = ['w', 'y', 'k', 'o', 'p'];
  2. const iterator = array.values();
  3. for (const value of iterator) {
  4. console.log(value); // 'w', 'y', 'k', 'o', 'p'
  5. }

三、数组应用实例

1.存储和处理数据:

JavaScript 数组经常用于存储和处理数据。例如,一个在线商店的产品列表可以表示为一个数组,每个产品是数组中的一个元素。通过数组方法可以对产品进行排序、过滤、搜索等操作。

  1. const products = [
  2. { id: 1, name: 'Product 1', price: 10 },
  3. { id: 2, name: 'Product 2', price: 20 },
  4. { id: 3, name: 'Product 3', price: 30 }
  5. ];
  6. // 对产品按价格排序
  7. const sortedProducts = products.sort((a, b) => a.price - b.price);
  8. // 过滤出价格大于 15 的产品
  9. const filteredProducts = products.filter(product => product.price > 15);
  10. // 搜索特定产品
  11. const searchProduct = products.find(product => product.name === 'Product 2');

2. 数据可视化:

JavaScript 数组常用于存储图表或图形数据,以便进行数据可视化。例如,一个简单的柱状图可以由一个数组表示,数组中的每个元素代表一个柱子的高度。

  1. const salesData = [100, 200, 300, 400, 500];
  2. // 绘制柱状图
  3. salesData.forEach((sales, index) => {
  4. // 绘制第 index+1 个柱子,高度为 sales
  5. });

3. 表单数据处理:

在 Web 开发中,经常需要处理表单数据。表单中的输入字段可以用一个数组来表示,每个字段是数组中的一个元素。这样可以方便地对表单数据进行验证、处理和提交。

  1. const formData = [
  2. { name: 'username', value: 'john_doe' },
  3. { name: 'password', value: '123456' },
  4. { name: 'email', value: 'john@example.com' }
  5. ];
  6. // 验证表单数据
  7. const isValid = formData.every(field => field.value !== '');
  8. // 提交表单数据
  9. function submitForm() {
  10. // 将 formData 转换为 JSON 格式并提交
  11. }

4. 游戏开发:

在游戏开发中,数组常用于表示游戏场景、角色、道具等。通过数组方法可以方便地管理游戏中的元素,如移动、碰撞检测、更新状态等。

  1. const gameScene = [
  2. [0, 0, 0, 0, 0],
  3. [0, 1, 1, 1, 0],
  4. [0, 1, 2, 1, 0],
  5. [0, 1, 1, 1, 0],
  6. [0, 0, 0, 0, 0]
  7. ];
  8. // 游戏角色移动
  9. function moveCharacter(x, y) {
  10. // 更新角色位置
  11. }
  12. // 碰撞检测
  13. function checkCollision(x, y) {
  14. // 检测角色是否与障碍物发生碰撞
  15. }

5.简单的待办事项列表应用程序(完整例子)

简单的待办事项列表应用程序。用户可以在输入框中添加新的待办事项,点击 "Add" 按钮后,该待办事项会被添加到列表中。用户可以点击已添加的待办事项来标记它们为已完成,已完成的待办事项会被显示为划线文本。

HTML 结构如下:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Todo List App</title>
  7. <link rel="stylesheet" href="styles.css">
  8. </head>
  9. <body>
  10. <div class="container">
  11. <h1>Todo List</h1>
  12. <input type="text" id="todoInput" placeholder="Add new todo">
  13. <button onclick="addTodo()">Add</button>
  14. <ul id="todoList"></ul>
  15. </div>
  16. <script src="script.js"></script>
  17. </body>
  18. </html>

CSS 样式(styles.css): 

  1. body {
  2. font-family: Arial, sans-serif;
  3. }
  4. .container {
  5. max-width: 400px;
  6. margin: 0 auto;
  7. padding: 20px;
  8. border: 1px solid #ccc;
  9. border-radius: 5px;
  10. }
  11. h1 {
  12. text-align: center;
  13. }
  14. input[type="text"] {
  15. width: 70%;
  16. padding: 8px;
  17. margin-bottom: 10px;
  18. }
  19. button {
  20. padding: 8px 20px;
  21. background-color: #007bff;
  22. color: #fff;
  23. border: none;
  24. border-radius: 5px;
  25. cursor: pointer;
  26. }
  27. button:hover {
  28. background-color: #0056b3;
  29. }
  30. ul {
  31. list-style-type: none;
  32. padding: 0;
  33. }
  34. li {
  35. margin-bottom: 5px;
  36. }
  37. .completed {
  38. text-decoration: line-through;
  39. color: #888;
  40. }

JavaScript 代码(script.js): 

  1. const todoList = [];
  2. function renderTodoList() {
  3. const list = document.getElementById('todoList');
  4. list.innerHTML = ''; // 清空列表
  5. todoList.forEach((todo, index) => {
  6. const li = document.createElement('li');
  7. li.textContent = todo.text;
  8. if (todo.completed) {
  9. li.classList.add('completed');
  10. }
  11. li.addEventListener('click', () => toggleTodoCompletion(index));
  12. list.appendChild(li);
  13. });
  14. }
  15. function addTodo() {
  16. const input = document.getElementById('todoInput');
  17. const text = input.value.trim();
  18. if (text !== '') {
  19. todoList.push({ text, completed: false });
  20. input.value = ''; // 清空输入框
  21. renderTodoList();
  22. }
  23. }
  24. function toggleTodoCompletion(index) {
  25. todoList[index].completed = !todoList[index].completed;
  26. renderTodoList();
  27. }
  28. // 初始化
  29. renderTodoList();

四、数组应用场景

  1. 数据存储和处理:数组经常用于存储和处理数据。无论是在前端还是后端开发中,都可以使用数组来存储数据,并通过数组的各种方法(如排序、过滤、映射、归约等)来对数据进行处理和操作。

  2. 列表和集合管理:在许多应用程序中,需要管理各种列表和集合,如待办事项列表、商品列表、用户列表等。使用数组可以方便地组织和管理这些列表和集合,并对其进行操作和更新。

  3. 数据可视化:在数据可视化应用中,数组常用于存储图表和图形数据。例如,柱状图、折线图、饼图等的数据通常以数组的形式进行表示,然后使用图表库将这些数据可视化展示出来。

  4. 游戏开发:在游戏开发中,数组被广泛用于表示游戏中的场景、角色、道具等。开发者可以使用数组来管理游戏中的各种元素,并通过数组的方法来实现游戏逻辑、碰撞检测、状态更新等功能。

  5. 表单数据处理:在 Web 开发中,表单是非常常见的交互元素。表单中的输入字段通常可以用一个数组来表示,开发者可以使用数组来处理和验证表单数据,并将其提交到服务器端进行进一步处理。

  6. 算法和数据结构:在算法和数据结构领域,数组是一种基础的数据结构,常用于实现各种算法和数据结构,如栈、队列、堆、哈希表等。通过数组,可以实现诸如搜索、排序、查找等各种常见的算法操作。

  7. 事件处理:在前端开发中,事件处理是非常重要的一部分。事件处理器通常将事件处理函数存储在数组中,当事件发生时,依次调用数组中的事件处理函数来处理事件。

  8. 动态编程和脚本化:在动态编程和脚本化环境中,如 Node.js、浏览器环境等,数组常用于存储和处理动态数据,并通过数组的方法来实现各种功能和逻辑。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/喵喵爱编程/article/detail/939670
推荐阅读
相关标签
  

闽ICP备14008679号