JS稀疏数组遍历问题

By yesmore on 2021-12-31
阅读时间 1 分钟
文章共 419
阅读量

同系列文章请查看:Github:pre-interview

JS稀疏数组遍历问题

前置知识:

  • JavaScript并没有常规的数组,所有的数组其实就是个对象,只不过会自动管理一些"数字"属性和length属性罢了。
  • JavaScript中的数组根本没有索引,因为索引应该是数字,而JavaScript中数组的索引其实是字符串:arr[1]其实就是arr[“1”],给arr[“1000”] = 1,arr.length也会自动变为1001。
  • JavaScript中的对象就是字符串到任意值的键值对。注意键只能是字符串

定义一个稀疏数组:

1
const arr = [1, , , 2, 3, , , 4, , , , , , , 5, 6, 7, , , 8]

数组中的空隙之间叫占位符 “empty”:一般用 null / undefined 占位;

其中,原始值占位一般用 undefined

分别使用 findforEach 方法遍历数组:

1
2
3
4
5
6
7
8
9
const arr = [1, , , 2, 3, , , 4, , , , , , , 5, 6, 7, , , 8]

arr.find(item => {
console.log('find: ' + item);
})

arr.forEach(item => {
console.log('forEach: ' + item);
})

打印结果:

为什么forEach忽略了空元素,而find不会忽略?

arr.find()

1
2
3
4
5
6
const arr = [1, , , 2, 3, , , 4, , , , , , , 5, 6, 7, , , 8]

const item = arr.find((item, index) => {
return index === 1
})
console.log(item); // undefined

在上面的程序中,使用了find来返回数组索引为1的元素,如果稀疏数组中的空元素(undefined)被忽略了的话,那就应该打印 2,既然如此 arr 不就相当于是 [1,2,3,4,5,6,7,8] 了吗?这显然是不合理的。这里要从find方法的目的来分析原因。

那为什么 forEach 会忽略空元素?这也要从 forEach 本身作用来看,forEach 的设计目的只是用来遍历数组


Tips: Please indicate the source and original author when reprinting or quoting this article.