foo = document.getElementById("outer");
function cycleIt() {
if (client.browser.Firefox) {
foo.addEventListener("animationend", updateClassName, true);
} else {
foo.addEventListener("webkitAnimationEnd", updateClassName, true);
}
}
function updateClassName() {
var z = foo.getAttribute("class");
if ( z == "a" ) {
foo.className = "b";
} else if ( z == "b" ) {
foo.className = "c"
} else if ( z == "c" ) {
foo.className = "d"
} else {
foo.className = "a"
}
return foo;
}
有人在Javascript聊天频道上告诉我,我应该为多个if-then语句制作一个哈希表。我该怎么做呢?
你创建了哈希表(它实际上只是一个普通对象):
var table = {
"a": "b",
"b": "c",
"c": "d"
};
然后使用该表将输入z
映射到输出(类名):
var z = foo.getAttribute("class");
foo.className = table[z] || "a";
return foo;
语法table[z] || "a"
是一种速记编写方法
if (table[z] === undefined) {
foo.className = "a";
}
else {
foo.className = table[z];
}
这两种样式并不完全等效,但在这种情况下(哈希中的所有值都是字符串,没有一个是空字符串),它的工作方式相同。
你要做的是将z
值映射到类名,如下所示:
function updateClassName() {
foo.className = ({
a: "b",
b: "c",
c: "d"
})[foo.className] || "a";
return foo;
}
对象文本是指定哪个旧值(键)应转到哪个新值(值)的映射。此外,它还使用 || "a"
来指定默认大小写。