当你想用javascript对象做为一个hash映射(彻底用来储存数据),你应该按以下方式来建立它。
const map = Object.create(null);
当建立一个映射使用对象字面量时(const map = {}),默认状况下,这个映射从这个对象继承属性。这和 Object.creatd(Object.prototype)建立时相等的。可是经过 Object.create(null),咱们明确指定 null 做为它的属性。所以它至关于没有属相,甚至没有constructor, toString, hasOwnProperty等方法。所以你能够随意使用这些键值在你的数据结构中,只要你须要。javascript
const dirtyMap = {}; const cleanMap = Object.create(null); dirtyMap.constructor // function Object() { [native code] } cleanMap.constructor // undefined // Iterating maps const key; for(key in dirtyMap){ if (dirtyMap.hasOwnProperty(key)) { // Check to avoid iterating over inherited properties. console.log(key + " -> " + dirtyMap[key]); } } for(key in cleanMap){ console.log(key + " -> " + cleanMap[key]); // No need to add extra checks, as the object will always be clean }
标注:若是你仅仅是想要用对象保存数据,建议这种方式:java
const map = Object.create(null)