当前位置: 首页 > news >正文

零基础学习JS--基础篇--索引集合类

数组是由名称和索引引用的值构成的有序列表。

JavaScript 中没有明确的数组数据类型。但是,你可以使用预定义的 Array 对象及其方法来处理应用程序中的数组。Array 对象具有以各种方式操作数组的方法,例如连接、反转和排序。它有一个用于确定数组长度的属性和用于正则表达式的其他属性。

创建数组

以下语句创建了等效的数组:

const arr1 = new Array(element0, element1, /* … ,*/ elementN);
const arr2 = Array(element0, element1, /* … ,*/ elementN);
const arr3 = [element0, element1, /* … ,*/ elementN];

element0, element1, …, elementN 是数组元素的值列表。当指定这些值时,数组将用它们作为数组的元素初始化。数组的 length 属性被设置为参数的数量。

括号语法称为“数组字面量”或“数组初始化式”。

为了创建一个长度不为 0,但是又没有任何元素的数组,可选以下任何一种方式:

// 这种方式...
const arr1 = new Array(arrayLength);// ...与这种方式会形成相同数组
const arr2 = Array(arrayLength);// 这个效果也一样
const arr3 = [];
arr3.length = arrayLength;

备注: 以上代码,arrayLength 必须为一个 Number。否则,将会创建一个只有单个元素(内含提供的值)的数组。调用 arr.length 会返回 arrayLength,但数组不包含任何元素。for...in 循环在数组上找不到任何属性。

如果你希望用单个元素初始化一个数组,而这个元素恰好又是 Number,那么你必须使用括号语法。当单个 Number 传递给 Array() 构造函数时,将会被解释为 arrayLength,并非单个元素。

// 创建一个只有唯一元素的数组:数字 42。
const arr = [42];// 创建一个没有元素的数组,且数组的长度被设置成 42。
const arr = Array(42);// 上面的代码与下面的代码等价:
const arr = [];
arr.length = 42;

如果 N 不是一个整数,调用 Array(N) 将会报 RangeError 错误,下面的例子说明了这种行为:

const arr = Array(9.3); // RangeError: Invalid array length

如果你需要创建任意类型的单元素数组,安全的方式是使用数组字面量。或者在向数组添加单个元素之前先创建一个空的数组。

你也可以使用 Array.of 静态方法来创建包含单个元素的数组。

const wisenArray = Array.of(9.3); // wisenArray 只包含一个元素:9.3

引用数组元素

因为元素也是属性,你可以使用属性访问器来访问。假设你定义了以下数组:

const myArray = ["Wind", "Rain", "Fire"];

你可以将数组的第一个元素引用为 myArray[0],将数组的第二个元素引用为 myArray[1],等等...元素的索引从零开始。

备注: 你也可以使用属性访问器来访问数组的其他属性,就像对象一样。

const arr = ["one", "two", "three"];
arr[2]; // three
arr["length"]; // 3

填充数组

你可以通过给数组元素赋值来填充数组,例如:

const emp = [];
emp[0] = "Casey Jones";
emp[1] = "Phil Lesh";
emp[2] = "August West";

备注: 如果你在以上代码中给数组运算符的是一个非整型数值,那么它将作为一个表示数组的对象的属性创建,而不是数组的元素。

const arr = [];
arr[3.4] = "Oranges";
console.log(arr.length); // 0
console.log(Object.hasOwn(arr, 3.4)); // true

你也可以在创建数组的时候去填充它:

const myArray = new Array("Hello", myVar, 3.14159);
// 或
const myArray = ["Mango", "Apple", "Orange"];
理解length:

在实现层面,JavaScript 实际上是将元素作为标准的对象属性来存储,把数组索引作为属性名。

length 属性是特殊的,如果存在最后一个元素,则其值总是大于其索引的正整数。

记住,JavaScript 数组索引是基于 0 的:它们从 0 开始,而不是 1。这意味着 length 属性将比最大的索引值大 1:

const cats = [];
cats[30] = ["Dusty"];
console.log(cats.length); // 31

你也可以给 length 属性赋值。

写一个小于数组元素数量的值将截断数组,写 0 会彻底清空数组:

const cats = ["Dusty", "Misty", "Twiggy"];
console.log(cats.length); // 3cats.length = 2;
console.log(cats); // [ 'Dusty', 'Misty' ] - Twiggy 已经被移除了cats.length = 0;
console.log(cats); // 输出 [],猫名称的数组现在已经空了cats.length = 3;
console.log(cats); // 输出 [ <3 empty items> ]
遍历数组:

一种常见的操作是遍历数组的值,以某种方式处理每个值。最简单的方法如下:

const colors = ["red", "green", "blue"];
for (let i = 0; i < colors.length; i++) {console.log(colors[i]);
}

forEach() 方法提供了遍历数组元素的其他方法:

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

传递给 forEach 的函数对数组中的每个元素执行一次,数组元素作为参数传递给该函数。未赋值的值不会在 forEach 循环迭代。

注意,在数组定义时省略的元素不会在 forEach 遍历时被列出,但是手动赋值为 undefined 的元素是被列出的:

const sparseArray = ["first", "second", , "fourth"];sparseArray.forEach((element) => {console.log(element);
});
// first
// second
// fourthif (sparseArray[2] === undefined) {console.log("sparseArray[2] 是 undefined"); // true
}const nonsparseArray = ["first", "second", undefined, "fourth"];nonsparseArray.forEach((element) => {console.log(element);
});
// first
// second
// undefined
// fourth
数组方法:

Array 对象具有下列方法:

concat() 方法连接两个或多个数组并返回一个新的数组。

let myArray = ["1", "2", "3"];
myArray = myArray.concat("a", "b", "c");
// myArray 现在是 ["1", "2", "3", "a", "b", "c"]

join() 方法将数组中的所有元素连接成一个字符串。

const myArray = ["Wind", "Rain", "Fire"];
const list = myArray.join(" - "); // list 现在是 "Wind - Rain - Fire"

push() 方法在数组末尾添加一个或多个元素,并返回数组操作后的 length

const myArray = ["1", "2"];
myArray.push("3"); // myArray 现在是 ["1", "2", "3"]

pop() 方法从数组移出最后一个元素,并返回该元素。

const myArray = ["1", "2", "3"];
const last = myArray.pop();
// myArray 现在是 ["1", "2"],last 为 "3"

shift() 方法从数组移出第一个元素,并返回该元素。

const myArray = ["1", "2", "3"];
const first = myArray.shift();
// myArray 现在是 ["2", "3"],first 为 "1"

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

const myArray = ["1", "2", "3"];
myArray.unshift("4", "5");
// myArray 变成了 ["4", "5", "1", "2", "3"]

slice() 方法从数组提取一个片段,并作为一个新数组返回。

let myArray = ["a", "b", "c", "d", "e"];
myArray = myArray.slice(1, 4); // [ "b", "c", "d"]
// 从索引 1 开始,提取所有的元素,直到索引 3 为止

at() 方法返回数组中指定索引处的元素,如果索引超出范围,则返回 undefined。它主要用于从数组末尾访问元素的负下标。

const myArray = ["a", "b", "c", "d", "e"];
myArray.at(-2); // "d",myArray 的倒数第二个元素

splice() 方法从数组移除一些元素,并(可选地)替换它们。它返回从数组中删除的元素。

const myArray = ["1", "2", "3", "4", "5"];
myArray.splice(1, 3, "a", "b", "c", "d");
// myArray 现在是 ["1", "a", "b", "c", "d", "5"]
// 本代码从 1 号索引开始(或元素“2”所在的位置),
// 移除 3 个元素,然后将后续元素插入到那个位置上。

reverse() 方法原地颠倒数组元素的顺序:第一个数组元素变为最后一个数组元素,最后一个数组元素变为第一个数组元素。它返回对数组的引用。

const myArray = ["1", "2", "3"];
myArray.reverse();
// 将原数组颠倒,myArray = [ "3", "2", "1" ]

flat() 方法返回一个新数组,所有子数组元素递归地连接到其中,直到指定的深度。

let myArray = [1, 2, [3, 4]];
myArray = myArray.flat();
// myArray 现在是 [1, 2, 3, 4],因为子数组 [3, 4] 已被展平

sort() 方法对数组的元素进行适当的排序,并返回对数组的引用,默认是升序排序。

const myArray = ["Wind", "Rain", "Fire"];
myArray.sort();
// 对数组排序,myArray = ["Fire", "Rain", "Wind"]

indexOf() 方法在数组中搜索 searchElement 并返回第一个匹配的索引。

const a = ["a", "b", "a", "b", "a"];
console.log(a.indexOf("b")); // 1// 再试一次,这次从最后一次匹配之后开始
console.log(a.indexOf("b", 2)); // 3
console.log(a.indexOf("z")); // -1, 因为找不到 'z'

lastIndexOf() 方法的工作原理类似于 indexOf,但这是从末尾开始,反向搜索。

const a = ["a", "b", "c", "d", "a", "b"];
console.log(a.lastIndexOf("b")); // 5// 再试一次,这次从最后一次匹配之前开始
console.log(a.lastIndexOf("b", 4)); // 1
console.log(a.lastIndexOf("z")); // -1

forEach() 方法对数组中的每个元素执行 callback 并返回 undefined

const a = ["a", "b", "c"];
a.forEach((element) => {console.log(element);
});
// 输出:
// a
// b
// c

map() 方法返回由每个数组元素上执行 callback 的返回值所组成的新数组。

const a1 = ["a", "b", "c"];
const a2 = a1.map((item) => item.toUpperCase());
console.log(a2); // ['A', 'B', 'C']

flatMap() 方法先执行 map(),再执行深度为 1 的 flat()

const a1 = ["a", "b", "c"];
const a2 = a1.flatMap((item) => [item.toUpperCase(), item.toLowerCase()]);
console.log(a2); // ['A', 'a', 'B', 'b', 'C', 'c']

filter() 方法返回一个新数组,其中包含 callback 返回 true 的元素。

const a1 = ["a", 10, "b", 20, "c", 30];
const a2 = a1.filter((item) => typeof item === "number");
console.log(a2); // [10, 20, 30]

find() 方法返回 callback 返回 true 的第一个元素。

const a1 = ["a", 10, "b", 20, "c", 30];
const i = a1.find((item) => typeof item === "number");
console.log(i); // 10

findLast() 方法返回 callback 返回 true 的最后一个元素。

const a1 = ["a", 10, "b", 20, "c", 30];
const i = a1.findLast((item) => typeof item === "number");
console.log(i); // 30

findIndex() 方法返回 callback 返回 true 的第一个元素的索引。

const a1 = ["a", 10, "b", 20, "c", 30];
const i = a1.findIndex((item) => typeof item === "number");
console.log(i); // 1

findLastIndex() 方法返回 callback 返回 true 的最后一个元素的索引。

const a1 = ["a", 10, "b", 20, "c", 30];
const i = a1.findLastIndex((item) => typeof item === "number");
console.log(i); // 5

如果 callback 对数组中的每一个元素都返回 true,则 every() 方法返回 true

function isNumber(value) {return typeof value === "number";
}
const a1 = [1, 2, 3];
console.log(a1.every(isNumber)); // true
const a2 = [1, "2", 3];
console.log(a2.every(isNumber)); // false

如果 callback 对数组中至少一个元素返回 true,则 some() 方法返回 true

function isNumber(value) {return typeof value === "number";
}
const a1 = [1, 2, 3];
console.log(a1.some(isNumber)); // true
const a2 = [1, "2", 3];
console.log(a2.some(isNumber)); // true
const a3 = ["1", "2", "3"];
console.log(a3.some(isNumber)); // false

稀疏数组

数组可以包含“空槽”,这与用值 undefined 填充的槽不一样。空槽可以通过以下方式之一创建:

// Array 构造函数:
const a = Array(5); // [ <5 empty items> ]// 数组字面量中的连续逗号:
const b = [1, 2, , , 5]; // [ 1, 2, <2 empty items>, 5 ]// 直接给大于 array.length 的索引设置值以形成空槽:
const c = [1, 2];
c[4] = 5; // [ 1, 2, <2 empty items>, 5 ]// 通过直接设置 .length 拉长一个数组:
const d = [1, 2];
d.length = 5; // [ 1, 2, <3 empty items> ]// 删除一个元素:
const e = [1, 2, 3, 4, 5];
delete e[2]; // [ 1, 2, <1 empty item>, 4, 5 ]

在某些操作中,空槽的行为就像它们被填入了 undefined 那样。

const arr = [1, 2, , , 5]; // 创建一个稀疏数组// 通过索引访问
console.log(arr[2]); // undefined// For...of
for (const i of arr) {console.log(i);
}// 输出:1 2 undefined undefined 5// 展开运算
const another = [...arr]; // "another" 为 [ 1, 2, undefined, undefined, 5 ]

在其他方法,特别是数组迭代方法时,空槽是被跳过的。

const mapped = arr.map((i) => i + 1); // [ 2, 3, <2 empty items>, 6 ]
arr.forEach((i) => console.log(i)); // 1 2 5
const filtered = arr.filter(() => true); // [ 1, 2, 5 ]
const hasFalsy = arr.some((k) => !k); // false// 属性迭代
const keys = Object.keys(arr); // [ '0', '1', '4' ]
for (const key in arr) {console.log(key);
}
// 输出:'0' '1' '4'
// 在对象中使用展开,使用属性枚举,而不是数组的迭代器
const objectSpread = { ...arr }; // { '0': 1, '1': 2, '4': 5 }

多维数组

数组是可以嵌套的,这就意味着一个数组可以作为一个元素被包含在另外一个数组里面。利用 JavaScript 数组的这个特性,可以创建多维数组。

以下代码创建了一个二维数组。

const a = new Array(4);
for (i = 0; i < 4; i++) {a[i] = new Array(4);for (j = 0; j < 4; j++) {a[i][j] = "[" + i + "," + j + "]";}
}

这个例子创建的数组拥有以下行数据:

Row 0: [0,0] [0,1] [0,2] [0,3]
Row 1: [1,0] [1,1] [1,2] [1,3]
Row 2: [2,0] [2,1] [2,2] [2,3]
Row 3: [3,0] [3,1] [3,2] [3,3]

使用数组存储其他属性

数组也可以像对象那样使用,以存储相关信息:

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

当一个数组作为字符串和正则表达式的匹配结果时,该数组将会返回相关匹配信息的属性和元素。

附:以上内容均为个人在MDN网站上学习JS的笔记,若有侵权,将在第一时间删除,若有错误,将在第一时间修改。

相关文章:

  • Xilinx 7系列FPGA的配置流程
  • QT----写完的程序打包为APK在自己的手机上运行
  • 设计MySQL数据表的几个注意点
  • python:布伊山德U检验(Buishand U test,BUT)突变点检测(以NDVI时间序列为例)
  • 「AI工程师」数据处理与分析-工作指导
  • c语言,大宗撮合交易中心系统核心模块代码
  • Toyota Programming Contest 2024#3(AtCoder Beginner Contest 344)(A~C)
  • 【C/C++】常量指针与指针常量的深入解析与区分(什么是const int * 与 int * const ?)
  • [渗透教程]-013-嗅探工具-wireshark操作
  • python脚本批量关闭exe文件
  • 数据分析-Pandas最简单的方法画矩阵散点图
  • 【leetcode】429. N 叉树的层序遍历
  • Excel转pdf
  • appium2的一些配置
  • 【Linux】线程同步与生产消费者问题
  • Apache Zeppelin在Apache Trafodion上的可视化
  • CSS居中完全指南——构建CSS居中决策树
  • el-input获取焦点 input输入框为空时高亮 el-input值非法时
  • Hibernate【inverse和cascade属性】知识要点
  • JavaScript实现分页效果
  • webgl (原生)基础入门指南【一】
  • 编写高质量JavaScript代码之并发
  • 从零搭建Koa2 Server
  • 基于Android乐音识别(2)
  • 记录一下第一次使用npm
  • 简析gRPC client 连接管理
  • 力扣(LeetCode)22
  • 正则与JS中的正则
  • 直播平台建设千万不要忘记流媒体服务器的存在 ...
  • #我与Java虚拟机的故事#连载08:书读百遍其义自见
  • (1)常见O(n^2)排序算法解析
  • (10)Linux冯诺依曼结构操作系统的再次理解
  • (173)FPGA约束:单周期时序分析或默认时序分析
  • (day 2)JavaScript学习笔记(基础之变量、常量和注释)
  • (MonoGame从入门到放弃-1) MonoGame环境搭建
  • (Redis使用系列) SpringBoot 中对应2.0.x版本的Redis配置 一
  • (笔记)Kotlin——Android封装ViewBinding之二 优化
  • (超详细)语音信号处理之特征提取
  • (定时器/计数器)中断系统(详解与使用)
  • (算法)Travel Information Center
  • (转)Linux NTP配置详解 (Network Time Protocol)
  • (转)memcache、redis缓存
  • (转)重识new
  • .equals()到底是什么意思?
  • .form文件_SSM框架文件上传篇
  • .net core控制台应用程序初识
  • .NET开发不可不知、不可不用的辅助类(三)(报表导出---终结版)
  • .NET开源项目介绍及资源推荐:数据持久层 (微软MVP写作)
  • .net利用SQLBulkCopy进行数据库之间的大批量数据传递
  • .net网站发布-允许更新此预编译站点
  • .NET中的Event与Delegates,从Publisher到Subscriber的衔接!
  • .sdf和.msp文件读取
  • @font-face 用字体画图标
  • @JsonSerialize注解的使用
  • [ HTML + CSS + Javascript ] 复盘尝试制作 2048 小游戏时遇到的问题