当前位置:网站首页>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 这些方法对于稀缺数组的处理。
文章链接
边栏推荐
- Prometeus 2.34.0 new features
- js强制转换
- ACL 2022 | 基于神经标签搜索的零样本多语言抽取式文本摘要
- Leetcode topic [array] -268- missing numbers
- The texstudio official website cannot be opened
- SIGIR 2022 | 港大等提出超图对比学习在推荐系统中的应用
- Microservice architecture practice: business management background and SSO design, SSO client design
- What is the difference between digital collections and NFT
- Problems encountered this week
- Kubernetes essential tools: 2021
猜你喜欢

Sandboxed container: container or virtual machine

Getting started with mongodb

Ndroid development from introduction to mastery Chapter 2: view and ViewGroup

Cache breakdown! Don't even know how to write code???

Niuke network: Design LRU cache structure design LFU cache structure

Community ownership of NFT trading market is unstoppable

halcon之区域:多种区域(Region)特征(5)

Interpretation of new plug-ins | how to enhance authentication capability with forward auth

类型多样的石膏PBR多通道贴图素材,速来收藏!

10 cloud security best practices that enterprises need to know
随机推荐
COMP5216 Mobile Computing Assignment 1 - Extending ToDoList app
mysql Add column 失败 因为之前有数据,不是默认null 不行
Use FST JSON to automatically generate faster JSON serialization methods
分布式架构概述
Teach you to learn dapr - 1 The era of net developers
国信证券怎么开户?通过链接办理股票开户安全吗
【推荐系统学习】推荐系统的技术栈
[recommendation system learning] recommendation system architecture
VSCode使用 - Remote-SSH 配置说明
Romance of the Three Kingdoms: responsibility chain model
Apache APIs IX has the risk of rewriting the x-real-ip header (cve-2022-24112)
【uniapp】uniapp手机端使用uni.navigateBack失效问题解决
7 views on NFT market prospect
用redis做用户访问数据统计HyperLogLog及Bitmap高级数据类型
[recommendation system learning] technology stack of recommendation system
Problems encountered this week
How sparksql returns a specific day of the week by date -dayofweek function
并发之线程安全
链游系统开发技术方案设计丨NFT链游系统开发流程及源码
Find out the maximum value of each column element of NxN matrix and store it in the one-dimensional array indicated by formal parameter B in order