< JavaScript小技巧:Array构造函数妙用 >

news/2024/7/7 22:03:01

在这里插入图片描述

文章目录

  • 👉 Array构造函数 - 基本概念
  • 👉 Array函数技巧用法
    • 1. Array.of()
    • 2. Array.from()
    • 3. Array.reduce()
    • 4. (Array | String).includes()
    • 5. Array.at()
    • 6. Array.flat()
    • 7. Array.findIndex()
  • 📃 参考文献
  • 往期内容 💨


今天这篇文章,主要想跟大家分享几个实用的Array方法使用小技巧,希望能够帮助到你。

下面我们开始今天的内容吧 ! !!

👉 Array构造函数 - 基本概念

与其他编程语言中的数组一样,Array 对象支持在单个变量名下存储多个元素,并具有执行常见数组操作的成员。

JavaScript 中,数组不是基本类型,而是具有以下核心特征的 Array 对象:

  • JavaScript 数组是可调整大小的,并且可以包含不同的数据类型。(当不需要这些特征时,可以使用类型化数组。)
  • JavaScript 数组不是关联数组,因此,不能使用任意字符串作为索引访问数组元素,但必须使用非负整数(或它们各自的字符串形式)作为索引访问。
  • JavaScript 数组的索引从 0 开始:数组的第一个元素在索引 0 处,第二个在索引 1 处,以此类推,最后一个元素是数组的 length 属性减去 1 的值。
  • JavaScript 数组复制操作创建浅拷贝。(所有 JavaScript 对象的标准内置复制操作都会创建浅拷贝,而不是深拷贝)。

👉 Array函数技巧用法

Array() 作为构造函数,原型链上绑定了许许多多的对数组类型进行操作的方法。其中包含了许多能提高数组操作性能的方法,接下来,让小温给大家讲讲吧!

1. Array.of()

Array.of() 方法通过可变数量的参数创建一个新的 Array 实例,而不考虑参数的数量或类型。

const array1 = Array(3) // [ , , ]
// 2. Set the initial value of the array
const array2 = Array() // []
const array3 = Array(undefined) // [ undefined ]
const array4 = Array(1, 2, 3) // [ 1, 2, 3 ]

传递给Array函数的参数个数不一样,其对应功能也不一样。但是如果我们只是想生成指定内容对应的数组时,Array()就显得不太好控制了。而在js中我们可以使用 Array.of 来弥补 Array 的不足。

Array.of(7); // [7]
Array(7); // [,,,,,,]

Array.of(1, 2, 3); // [1, 2, 3]
Array(1, 2, 3);    // [1, 2, 3]


// it's not initializing an array of length 3
const array1 = Array.of(3) // [ 3 ]
const array2 = Array.of() // []
const array3 = Array.of(undefined) // [ undefined ]
const array4 = Array.of(1, 2, 3) // [ 1, 2, 3 ]

2. Array.from()

从方法中,我们可以通过 Array.from 方法将类数组对象、arguments 对象和 NodeList 对象转换为真正的数组。

  • 类数组对象
const arrayLike = {
  0: 'fatfish',
  1: 'medium',
  length: 2
}
const array1 = [].slice.call(arrayLike) // ['fatfish', 'medium']
// A more convenient way
const array2 = Array.from(arrayLike) // ['fatfish', 'medium']
  • 节点列表
const domsNodeList = document.querySelectorAll('div')
const domsArray = Array.from(domsNodeList) // [ dom, dom, dom, ... ]
  • Arguments
const logInfo = function () {
  console.log('arguments', arguments)
  console.log('Array.from arguments', Array.from(arguments))
}
logInfo('fatfish', 100)
logInfo('fatfish')
  • Array.from的第二个参数
const array = [ 1, 2, 3 ]
const array2 = array.map((num) => num * 2) // [2, 4, 6]
const array3 = Array.from(array, (num) => num * 2) // [2, 4, 6]

3. Array.reduce()

reduce() 方法对数组中的每个元素按序执行一个由您提供的 reducer 函数,每一次运行 reducer 会将先前元素的计算结果作为参数传入,最后将其结果汇总为单个返回值。

第一次执行回调函数时,不存在“上一次的计算结果”。如果需要回调函数从数组索引为 0 的元素开始执行,则需要传递初始值。

语法

array.reduce((previousValue, currentValue, currentIndex, array) => {
	/* … */
}, initialValue)
  • previousValue:上一次调用 callbackFn 时的返回值。在第一次调用时,若指定了初始值。
  • initialValue,其值则为 initialValue,否则为数组索引为 0 的元素 array[0]。
  • currentValue:数组中正在处理的元素。在第一次调用时,若指定了初始值 initialValue,其值则为数组索引为 0 的元素 array[0],否则为 array[1]。
  • currentIndex:数组中正在处理的元素的索引。若指定了初始值 initialValue,则起始索引号为 0,否则从索引 1 起始。
  • array:用于遍历的数组。
  • initialValue 可选

注:作为第一次调用 callback 函数时参数 previousValue 的值。若指定了初始值 initialValue,则 currentValue 则将使用数组第一个元素;否则 previousValue 将使用数组第一个元素,而 currentValue 将使用数组第二个元素。

返回值: 使用“reducer”回调函数遍历整个数组后的结果。

应用场景

  1. 数值数组累加
const array1 = [1, 2, 3, 4];

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (accumulator, currentValue) => accumulator + currentValue,
  initialValue
);
  1. 利用数组实现哈希功能

根据实际功能将数组变成需要使用的对象结构或者其他结构, 但是该结构长度等于原数组的长度,reduce根据原数组的长度循环执行的。

/* 已报名名单 - 判断是否报名 */
const array1 = ['小红', '张三', '王五', '小明'];
const obj = array1.reduce((pre, curr) => {
	pre[curr] = true;
	return pre
},{});

console.log(obj) // { '小红': true, ... }

console.log(obj['小明']) // true

4. (Array | String).includes()

我们经常会写这样的判断语句,在满足其中一个条件的情况下做某事。或者是匹配数组中是否包含某个值、字符串中是否包含某个指定的字符串之类的。

includes() 方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回 false

语法

includes(searchElement)
includes(searchElement, fromIndex)

includes函数中,必须传递第一个参数,代表需要搜索的参数。第二个则代表从数组 | 字符串的fromIndex 下标位置开始搜索,如果不传,则从头开始搜索。

注: 当指定下标超过被搜索对象的长度时,直接不进行搜索,返回false

// 数组
const array1 = [1, 2, 3];

console.log(array1.includes(2));
// Expected output: true

const pets = ['cat', 'dog', 'bat'];

console.log(pets.includes('cat'));
// Expected output: true

console.log(pets.includes('at'));
// Expected output: false

// 字符串
const str = 'abcdefg';

console.log(str.includes('abc'));
// Expected output: true

console.log(pets.includes('bac'));
// Expected output: false


// 也可以将 arr|str.includes()当作判断条件使用
const nums = [ 1, 2, 3, 4 ]
const num = 1
if (nums.includes(num)) {
  console.log(num) // 1
}

5. Array.at()

你如何读取数组的尾部元素?
是的,我们需要以“array.length-1”作为下标来读取。

const array = [ 1, 2, 3, 4, 5 ]
const lastEle = array[ array.length - 1 ] // 5
// You can't read like that
const lastEle = array[ - 1 ] // undefined

还有别的办法吗?
是的,“at”方法将成为您的魔法。当然,可以使用 at(index) 读取数组中其他位置的元素。

const array = [ 1, 2, 3, 4, 5 ]
const lastEle = array.at(-1) // 5
const ele1 = array.at(0) // 1

6. Array.flat()

flat() 方法创建一个新数组,其中所有子数组元素以递归方式连接到指定深度。

const array = [ 1, [ 2, [ 3, [ 4, [ 5 ] ] ] ] ]
// The default depth is 1
const flat1 = array.flat() // [ 1, 2, [ 3, [ 4, [ 5 ] ] ] ]
const flat2 = array.flat(2) // [ 1, 2, 3, [ 4, [ 5 ] ] ]
const flatAll = array.flat(Infinity) // [ 1, 2, 3, 4, 5 ]

7. Array.findIndex()

findIndex() 方法与 find()返回整个数组项不同,findIndex() 返回数组中满足提供的测试函数的第一个元素的下标索引。否则,它返回 -1,表示没有元素通过测试。”

const array = [ -1, 0, 10, 10,  20, 100 ]
const index1 = array.findIndex((num) => num < 0) // 0
const index2 = array.findIndex((num) => num >= 10) // 2

📃 参考文献

  • Array构造函数文档 - MDN (点击跳转)
  • 6 个让你少写多做的 ES6 技巧

往期内容 💨

🔥 < elementUI组件样式及功能补全: 实现点击steps组件跳转对应步骤 >

🔥 < CSDN周赛解析:第 28 期 >

🔥 < elementUi 组件插件: el-table表格拖拽修改列宽及行高 及 使用注意事项 >

🔥 < 每日小技巧:N个很棒的 Vue 开发技巧, 持续记录ing >


http://lihuaxi.xjx100.cn/news/978119.html

相关文章

项目实战典型案例23——-注册上nacos上的部分服务总是出现频繁掉线的情况

注册上nacos上的部分服务总是出现频繁掉线的情况一&#xff1a;背景介绍二&#xff1a;思路&方案解决问题过程涉及到的知识nacos服务注册和服务发现一&#xff1a;背景介绍 spring cloud项目通过nacos作为服务中心和配置中心&#xff0c;出现的问题是其中几个服务总是出现…

基于Three.js和MindAR实现的网页端WebAR人脸识别追踪功能的京剧换脸Demo(含源码)

前言 近段时间一直在玩MindAR的功能&#xff0c;之前一直在弄图片识别追踪的功能&#xff0c;发现其强大的功能还有脸部识别和追踪的功能&#xff0c;就基于其面部网格的例子修改了一个国粹京剧的换脸程序。如果你不了解MindAR的环境配置可以先参考这篇文章&#xff1a;基于Mi…

[nodejs开发] typescript引入js模块或文件

首先更改tsconfig.json 中的compilerOptions属性&#xff1a;"moduleResolution": "Node"假设有一个abc.js其内容如下&#xff1a;var Circle (function () {function Circle() {}Circle.prototype.draw function () {console.log("Cirlce is drawn…

JavaScript 高级实例集合

文章目录JavaScript 高级实例集合创建一个欢迎 cookie简单的计时另一个简单的计时在一个无穷循环中的计时事件带有停止按钮的无穷循环中的计时事件使用计时事件制作的钟表创建对象的实例创建用于对象的模板JavaScript 高级实例集合 创建一个欢迎 cookie 源码 <!DOCTYPE ht…

Cobalt Strike---(2)

数据管理 Cobalt Strike 的团队服务器是行动期间Cobalt Strike 收集的所有信息的中间商。Cobalt Strike 解析来 自它的 Beacon payload 的输出&#xff0c;提取出目标、服务和凭据。 如果你想导出 Cobalt Strike 的数据&#xff0c;通过 Reporting → Export Data 。Cobalt Str…

软件测试-性能测试-基础知识

文章目录 1.性能测试理论1.1 相关概念1.2 性能测试指标2.性能测试策略2.1 基准测试2.2 负载测试2.3 稳定性测试2.4 其他测试策略3.性能测试的流程3.1 需求分析3.2 编写性能测试计划和方案3.3 编写性能测试用例3.4 性能测试执行3.5 性能测试报告4.性能测试工具4.1 Loadrunner4.2…

verilog specify语法

specify block用来描述从源点&#xff08;source&#xff1a;input/inout port&#xff09;到终点&#xff08;destination&#xff1a;output/inout port&#xff09;的路径延时&#xff08;path delay&#xff09;&#xff0c;由specify开始&#xff0c;到endspecify结束&…

dotConnect Universal 4.0.134 Crack

dotConnect Universal 能够呈现和访问不同于Microsoft 和框架的数据库的信息。网。它能够支持大多数数据库服务器以及 Microsoft Access、Oracle、MySQL、DB2、PostgreSQL、SQLite、InterBase、FireBird&#xff0c;最后是 Microsoft SQL Server。它可以通过 ODBC、OLE DB、ADO…