我使用对象作为地图并使用模式映射将对象存储在其中[obj.href] = obj
我期待重复的密钥,但发生了一些非常奇怪的事情:
我有2个完全不同的(每个字段)对象存储不同的键,但是当第3个对象具有与1st相同的键时,查找返回第2个对象(使用不同的键存储),当我执行查找返回的对象的href,我再次获得相同的对象,就像2个键是等效的一样。
根据Which characters are valid/invalid in a JSON key name?以及SO上的其他一些帖子,任何有效字符串都可以是对象中的一个键,并且您不需要转义任何字符,我担心因为所有字符' /'和'#' s。
我确定我的代码中只是一个简单的错误,我无法看到它,因为它已经是上午8点,而且我已经整晚都在玩。任何帮助发现它将不胜感激。
function parseSpellsList($)
{
var spellsList = {};
$("ul[class|='link'],ul[class$='level']").each(function() {
var obj, spell_type, links, i, link, a, span, prevObj, hashKey;
obj = {};
links = this.children;
for (i=0; i<links.length; i++) {
link = links[i];
a = link.children[0];
obj.href = a.href.replace("file:///home/ckot/rpg_app/", "").replace("scripts/", "");
obj.name = a.innerHTML.replace("<b>", "").replace("</b>", "");
hashKey = obj.href;
prevObj = null;
if ( !(spellsList.hasOwnProperty(hashKey))) {
// debug code
if ("Blood Blaze" === obj.name || "Vomit Swarm" === obj.name) {
console.log("storing " + JSON.stringify(obj, null, " ") + " with hashKey: " + hashKey);
}
spellsList[hashKey] = obj;
} else {
console.log("\nWARNING: hashKey " + hashKey + " already exists");
prevObj = spellsList[hashKey];
console.log("object we which to store with hashKey: " + hashKey + "\n" + JSON.stringify(obj, null, " ")) ;
console.log("object retrieved with hashKey: " + hashKey + "\n" + JSON.stringify(prevObj, null, " "));
console.log("object retrieved with hashKey: " + prevObj.href + "\n" + JSON.stringify(spellsList[prevObj.href], null, " ") + "\n");
}
}
});
}
当我运行它时,我得到以下输出:
storing {
"href": "advancedRaceGuide/featuredRaces/orcs.html#blood-blaze",
"name": "Blood Blaze"
} with hashKey: advancedRaceGuide/featuredRaces/orcs.html#blood-blaze
storing {
"href": "advanced/spells/vomitSwarm.html#vomit-swarm",
"name": "Vomit Swarm"
} with hashKey: advanced/spells/vomitSwarm.html#vomit-swarm
WARNING: hashKey advancedRaceGuide/featuredRaces/orcs.html#blood-blaze already exists
object we which to store with hashKey: advancedRaceGuide/featuredRaces/orcs.html#blood-blaze
{
"href": "advancedRaceGuide/featuredRaces/orcs.html#blood-blaze",
"name": "Blood Blaze"
}
object retrieved with hashKey: advancedRaceGuide/featuredRaces/orcs.html#blood-blaze
{
"href": "advanced/spells/vomitSwarm.html#vomit-swarm",
"name": "Vomit Swarm"
}
object retrieved with hashKey: advanced/spells/vomitSwarm.html#vomit-swarm
{
"href": "advanced/spells/vomitSwarm.html#vomit-swarm",
"name": "Vomit Swarm"
}
编辑:
仅针对某些情况我使用:
node v0.10.22
npm v1.4.24
and the npm modules:
jsdom v1.0.0-pre.3
jquery v2.1.1",
答案 0 :(得分:0)
nvm,我在$ .each()的开头初始化obj而不是嵌套的for循环。 :(
我想我只是需要睡一觉。