当前位置:网站首页>Difference between Object and Map
Difference between Object and Map
2022-07-30 19:02:00 【Pushed open the door of the world】
Object
- 在ECMAScript中,Object是一个特殊的对象.它本身是一个顶级对象,同时还是一个构造函数,可以通过它(如:new Object())来创建一个对象.我们可以认为JavaScript中所有的对象都是Object的一个实例,对象可以用字面量的方法const obj = {}即可声明.
Map
- Map是Object的一个子类,可以有序保存任意类型的数据,使用键值对去存储,其中键可以存储任意类型,通过const m = new Map();即可得到一个map实例.
访问
map: 通过
map.get(key)方法去属性, 不存在则返回undefinedobject: 通过
obj.a或者obj[‘a’]去访问一个属性, 不存在则返回undefined
赋值
map: 通过map.set去设置一个值,
key可以是任意类型object: 通过object.a = 1或者object[‘a’] = 1,去赋值,key只能是字符串,数字或symbol
删除
map: 通过map.delete去删除一个值,试图删除一个不存在的属性会返回false
object: 通过delete操作符才能删除对象的一个属性,诡异的是,即使对象不存在该属性,删除也返回true,当然可以通过Reflect.deleteProperty(target, prop) 删除不存在的属性还是会返回true.
var obj = {}; // undefined
delete obj.a // true
大小
map: 通过map.size即可快速获取到内部元素的总个数
object: 需要通过Object.keys的转换才能将其转换为数组,再通过数组的length方法去获得或者使用Reflect.ownKeys(obj)也可以获取到keys的集合
Reflect.ownKeys 可以获取所有的keys
迭代
map: 拥有迭代器,可以通过for-of forEach去直接迭代元素,且
The traversal order is deterministicobject: 并没有实现迭代器,需要自行实现,不实现只能通过for-in循环去迭代,
遍历顺序是不确定的
Because objects are optimized for properties,排序属性 elements,用来存储数字. 常规属性 properties 用来存储字符串.数字属性应该按照索引值⼤⼩升序排列,字符串属性根据创建时的顺序升序排列.并且数字属性优先于字符串.So there will be cases where the traversal order is uncertain.
快属性就是采用线性数据结构,慢属性就是采用非线性结构,比如字典来存储数据
使用场景
如果只需要简单的存储key-value的数据,并且key不需要存储复杂类型的,直接用对象
如果该对象必须通过JSON转换的,则只能用对象,目前暂不支持Map
map的阅读性更好,所有操作都是通过api形式去调用,更有编程体验,比如要make a caching strategy
(() => {
let arr = [1, 2, 3, 1, 2];
const unique = (arr) => {
let map = new Map();
let res = [];
for (let k of arr) {
if (!map.has(k)) {
map.set(k);
res.push(k);
}
}
return res;
};
console.log(unique(arr));
})();
边栏推荐
猜你喜欢

Pytorch基础--tensorboard使用(一)

Recommendation | People who are kind to you, don't repay them by inviting them to eat

好未来单季营收2.24亿美元:同比降84% 张邦鑫持股26.3%

OMP: Error #15: Initializing libiomp5md.dll, but found libiomp5md.dll already initialized.解决方法

vxe-table实现复选框鼠标拖动选中

Codeblocks + Widgets 创建窗口代码分析

VS Code 连接SQL Server

【每日一道LeetCode】——191. 位1的个数

开心的聚餐

- daily a LeetCode 】 【 191. A number of 1
随机推荐
Anaconda Navigator卡在loading applications
Tensorflow2.0 混淆矩阵与打印准确率不符
卫星电话是直接与卫星通信还是通过地面站?
CIMC Shilian Dafeitong is the global industrial artificial intelligence AI leader, the world's top AI core technology, high generalization, high robustness, sparse sample continuous learning, industri
【Pointing to Offer】Pointing to Offer 22. The kth node from the bottom in the linked list
电脑死机的时候,发生了什么?
荐号 | 对你有恩的人,不要请吃饭来报答
【每日一道LeetCode】——191. 位1的个数
【Pointing to Offer】Pointing to Offer 18. Delete the node of the linked list
Critical Reviews | A review of the global distribution of antibiotics and resistance genes in farmland soil by Nannong Zou Jianwen's group
终端分屏工具Terminalx的使用
Anaconda Navigator stuck on loading applications
第十七届“振兴杯”全国青年 职业技能大赛——计算机程序设计员(云计算平台与运维)参赛回顾与总结
AWS 控制台
深入浅出边缘云 | 3. 资源配置
[Summary] 1396- 60+ VSCode plugins to create a useful editor
MySql中@符号的使用
架构师如何成长
攻防世界web-Cat
微信小程序云开发 | 城市信息管理