当前位置:网站首页>map和filter方法对于稀缺数组的处理
map和filter方法对于稀缺数组的处理
2022-06-26 17:23:00 【丹丹的小跟班】
稀缺数组
有一种数组叫稀缺数组,他的特点就是含有未赋值的索引。
比如:
let arr = [1]
arr.length = 10
这样一个数组长度为10,但是,除了第一位为1之外,其余的都是空,也就是使用了empty 字段占位。而map和filter作为最常用的数组方法之一,对于这种稀缺数组的处理是怎样的呢?
filter
任何问题首先看官方文档。
filter 为数组中的每个元素调用一次 callback 函数,并利用所有使得 callback 返回 true 或等价于 true 的值的元素创建一个新数组。callback 只会在已经赋值的索引上被调用,
对于那些已经被删除或者从未被赋值的索引不会被调用。那些没有通过 callback 测试的元素会被跳过,不会被包含在新数组中。
官方文档清晰的表示了filter对于稀缺数组的处理。那就是不会对稀缺数组里面的空值进行回调函数的调用,并且最终结果会自动排除空值,这其实可以算一个很好的在数组里面排除空值的方法。
map
我们只要注意官方文档的这样一句话:根据规范中定义的算法,如果被map调用的数组是离散的,新数组将也是离散的保持相同的索引为空。有人可能对离散表示疑惑,我们可以简单理解为就是稀缺数组,数组里面存在‘孔’,也就是空值(不是空字符串)。
var array = [1,,,2]
var mapArray = array.map((item, index) => {
console.log(index) //0, 3
return item + 1;
})
// 方法执行是打印 0,3 似乎跳过了数组中 hole 元素
console.log(mapArray) //[2, empty × 2, 3]
经测试发现map方法是将空值直接跳过不进行运算(这里跟filter一直),但是会在最终结果保留空值(这里跟filter又不一致)。
补充
当然除了filter和map之外,还有一些数组方法也会遇到这些情况,这里分享一篇看到的文章,文章里还介绍了findIndex,find ,forEach ,reduce 这些方法对于稀缺数组的处理。
文章链接
边栏推荐
- sparksql如何通过日期返回具体周几-dayofweek函数
- 并发之Synchronized说明
- The function keeps the value of variable H to two decimal places and rounds the third digit
- Teach you to learn dapr - 2 Must know concept
- Implementation of MySQL master-slave architecture
- A simple membership card management system based on Scala
- The king of Internet of things protocol: mqtt
- Teach you to learn dapr - 6 Publish subscription
- Leetcode topic [array] -268- missing numbers
- Interpretation of new plug-ins | how to enhance authentication capability with forward auth
猜你喜欢

【推荐系统学习】推荐系统架构

Microservice architecture practice: user login and account switching design, order query design of the mall

Distributed Architecture Overview

Teach you to learn dapr - 3 Run the first with dapr Net program
![[buuctf.reverse] 126-130](/img/df/e35633d85caeff1dece62a66cb7804.png)
[buuctf.reverse] 126-130

Turtle cartography

What is the difference between digital collections and NFT

二分查找-2

20:第三章:开发通行证服务:3:在程序中,打通redis服务器;(仅仅是打通redis服务器,不涉及具体的业务开发)

Daily record 2
随机推荐
Incomplete line spacing adjustment of formula display in word
分布式架构概述
Synchronized description of concurrency
LeetCode——226. Flip binary tree (BFS)
Leetcode HOT100 (22--- bracket generation)
Find all primes less than or equal to Lim, store them in AA array, and return the number of primes
[dynamic planning] Jianzhi offer II 091 Paint the house
Wechat app mall, review products, upload commodity pictures, and score Commodity Services
#25class的类继承
类型多样的石膏PBR多通道贴图素材,速来收藏!
[suggested collection] 11 online communities suitable for programmers
Romance of the Three Kingdoms: responsibility chain model
【万字总结】以终为始,详细分析高考志愿该怎么填
The texstudio official website cannot be opened
在国金证券开户怎么样?开户安全吗?
9、智慧交通项目(2)
Apache APIs IX has the risk of rewriting the x-real-ip header (cve-2022-24112)
20:第三章:开发通行证服务:3:在程序中,打通redis服务器;(仅仅是打通redis服务器,不涉及具体的业务开发)
When I was in the library, I thought of the yuan sharing mode
sparksql如何通过日期返回具体周几-dayofweek函数