【发布时间】:2014-08-26 12:21:51
【问题描述】:
我使用一个对象作为映射,并使用模式 map[obj.href] = obj 在其中存储对象
我期待重复的键,但发生了一些非常奇怪的事情:
我有 2 个完全不同的(每个字段)对象,它们使用不同的键存储,但是当第三个对象与第一个具有相同的键时,查找将返回第二个对象(使用不同的键存储),当我执行查找返回对象的href,我又得到了同一个对象,好像两个键是等价的。
根据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",
【问题讨论】:
-
尝试创建一个可以共享的测试环境。好的平台是 liveweave.com、codepen.io 和 jsfiddle.net
-
@Max 我不得不使用 cloud9,因为我需要一个 node js 环境。除了使用 cloud9 用户名或电子邮件地址外,我无法明确共享,但是当人们连接到 ide.c9.io/ckot/ckotz_node_playground 时,我可以手动批准他们,您只需要在命令行运行 ./parseSpellList
标签: javascript object key