js中的Array的empty

声明一个数组长度的时候,如果这个数组的现有长度小于声明长度,那么数组后面就会被empty填满,直到达到声明长度

正文

因为最近业务中写到,数据存进一个数组中,数组长度固定,但是数据不一定够或者数据有可能多。如果数据够的话,多余的部分就会被截掉,如果数据不够的时候,后面就会empty

固定数组长度

固定数组长度有两种方法:

1
2
3
4
5
6

const arr = []
arr.length = 3

// 第二种,构造函数声明
const arr1 = new Array(4)

最后得到的结果都为[empty, empty, empty, empty]

操作含有empty的数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const arr = new Array(4)

arr[0] // undefined
Array.from(arr) // 返回一个数组[undefined, undefined, undefined, undefined]
arr.map((item) => item) // 遍历的那项为空时,返回empty
arr.forEach((item) => item) // 遍历的那项为空时,返回empty
arr.some((item) => item === undefined) // 遍历时会跳过为empty的项,如果数组为空则返回false
arr.every((item) => item === undefined) // 遍历时会跳过为empty的项,如果数组为空则返回true
arr.reduce((a, b) => a + b) // 数组为空时报错,报错信息为reduce操作的数组不能为空
arr.find((item) => item === undefined) // 能正常遍历,并返回找到的值undefined
arr.findIndex((item) => { // 能正常遍历,并返回找到的值的index
return item === undefined
})
arr.filter((item) => item === undefined)// 遍历时会跳过为empty的项
arr.join() // 返回一个',,,'的字符串
arr.includes() // 不传参数时为true,经过测试断定默认值为undefined
arr.indexOf() // 返回-1,经过测试断定默认值为undefined,但是它不对空数组判断
arr.sort() // 能正常排序,为empty的元素会被排序到最后
arr.fill(1) // 数组内所有项都会变成1
// pop, push, shift, unshift的操作都是正常进行
博主教你手撸JVM 开源项目
https://github.com/anons-org/nada
https://gitee.com/grateful/nada

博主长期对外收徒,欢迎咨询。
《编程语言设计和实现》《MUD游戏开发》《软件破解和加密》《游戏辅助外挂》《JAVA开发》 以上课程非诚勿扰!



=================================
QQ:184377367
GOLang Q群:6848027
电子电路入门群 436173132
C/C++/QT群 1414577
单片机嵌入式群 306312845
MUD/LIB/巫师交流群 391486684
java/springboot/hadoop/ 群 4915800
WEB前端开发交流群 214737701
操作系统研发群:15375777
Linux公社Q群:812742841
汇编/辅助/破解新手群:755783453
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

原文地址:https://www.cnblogs.com/cfas/p/15077753.html