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

在这里插入图片描述


今天这篇文章,主要想跟大家分享几个实用的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

📃 参考文献

往期内容 💨

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

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

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

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

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

技术宅小温

你小小的鼓励,是我搬砖的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值