使用Javascript哈希表为多个如果Thens

dma*_*man 1 javascript hashtable

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;
}
Run Code Online (Sandbox Code Playgroud)

有人在Javascript聊天频道上告诉我,我应该为if if语句创建一个哈希表.我该怎么办呢?

Jon*_*Jon 5

您创建哈希表(它实际上只是一个普通对象):

var table = {
    "a": "b",
    "b": "c",
    "c": "d"
};
Run Code Online (Sandbox Code Playgroud)

然后使用该表将输入映射z到输出(类名):

var z = foo.getAttribute("class");
foo.className = table[z] || "a";
return foo;
Run Code Online (Sandbox Code Playgroud)

语法table[z] || "a"是一种简写的写法

if (table[z] === undefined) {
    foo.className = "a";
}
else {
    foo.className = table[z];
}
Run Code Online (Sandbox Code Playgroud)

这两种样式并不完全等效,但在这种情况下(散列中的所有值都是字符串,它们都不是空字符串)它的工作方式相同.