对象和新的集合类型Map结构上十分的相似,对采用key-value
对的形式。但语法上还是有差异,比如定义一个对象和定义一个Map。
1.定义差异
定义一个对象可以采用对象字面量的形式,或者使用dot .
操作符来定义各个属性,而Map只能使用构造器或者 set
方法:
var myMap = new Map([["name", "James"], ["age", 26]]);
myMap.set("job", "software engineer");
定义对象:
var obj = {};
obj.name = "James";
obj.age = 26;
obj.job = "software engineer";
// 或者
var obj = {
name: "James",
age: 26,
job: "software engineer"
};
2.Map构造器中传入对象
我们知道Map构造器中只能传入数组,不能传入对象,但是我们可以通过一个npm包 mapify 来弥补这个缺失:
import{mapify} from "es6-mapify";
var map = mapify({name: "james", age: 26});
// map: Map {"name" => "james", "age" => 26}
// 同样我们可以通过另一个包将map集合转变成对象
import{demapify} from "es6-demapfy";
var demap = demapify(map);
// demap: {name: "james", age: 26}
3.将一个对象转换成Map集合
Map集合自身是可迭代的,因此有很多方法可以使用,比如 keys()
,values()
,entrties()
,forEach()
等等
对象: 比如游戏中的一些参数
var charSet = {
aler102:{id:"aler102", name:"Aleria", gender:"female",vocation:"mage",species:"half-elf"},
thor319:{id:"thor312", name:"Thor", gender:"male",vocation:"warrior",species:"half-orc"},
rean831:{id:"rean831", name:"Reanna", gender:"female",vocation:"monk",species:"human"},
gunt615:{id:"gunt615", name:"Gunther", gender:"male",vocation:"smith",species:"human"},
ness789:{id:"ness789", name:"Nessa", gender:"female",vocation:"mage",species:"human"}
}
利用 Object.keys()
将对象中的键值变为数组, 然后 使用 forEach()
转换成Map集合
var myMap = new Map();
Object.keys(charSet).forEach( key => {
myMap.set(key, charSet[key]);
});
// 现在myMap为:
Map {
"aler102" => Object {id: "aler102", name: "Aleria", gender: "female", vocation: "mage", species: "half-elf"},
"thor319" => Object {id: "thor312", name: "Thor", gender: "male", vocation: "warrior", species: "half-orc"},
"rean831" => Object {id: "rean831", name: "Reanna", gender: "female", vocation: "monk", species: "human"},
"gunt615" => Object {id: "gunt615", name: "Gunther", gender: "male", vocation: "smith", species: "human"},
"ness789" => Object {id: "ness789", name: "Nessa", gender: "female", vocation: "mage", species: "human"}
}
可以利用Map集合对其中的数据进行操作,比如说取出摸个键值对:
var targetMap = new Map();
myMap.forEach(function(value, key, ownerMap) {
if (value.gender === "male" && value.vocation === "smith") {
targetMap.set(key, value);
}
});
// targetMap:
Map {
"gunt615" => Object {id: "gunt615", name: "Gunther", gender: "male", vocation: "smith", species: "human"}
}
原文地址ES5 Objects vs. ES6 Maps – The differences and similarities