對象和新的集合類型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構造器中只能傳入數(shù)組悦析,不能傳入對象,但是我們可以通過一個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()
等等
對象: 比如游戲中的一些參數(shù)
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()
將對象中的鍵值變?yōu)閿?shù)組, 然后 使用 forEach()
轉換成Map集合
var myMap = new Map();
Object.keys(charSet).forEach( key => {
myMap.set(key, charSet[key]);
});
// 現(xiàn)在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集合對其中的數(shù)據(jù)進行操作挡鞍,比如說取出摸個鍵值對:
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