对象和字典一样,可以用来存储键/值对。如果你的数据跟对象一样,你可以用对象来查找你想要的值,而不是使用switch或if/else语句。当你知道你的输入数据在某个范围时,这种查找方式极为有效。
- 使用switch语句
function phoneticLookup(val) {
var result = "";
switch(val) {
case "alpha":
result = "Adams";
break;
case "bravo":
result = "Boston";
break;
case "charlie":
result = "Chicago";
break;
case "delta":
result = "Denver";
break;
case "echo":
result = "Easy";
break;
case "foxtrot":
result = "Frank";
}
return result;
}
// 测试
phoneticLookup("charlie");
- 把switch语句转化为一个叫做lookup的对象达到同样效果
function phoneticLookup(val) {
var result = "";
var lookup = {
alpha: "Adams",
bravo: "Boston",
charlie: "Chicago",
delta: "Denver",
echo: "Easy",
foxtrot: "Frank"
};
result = lookup[val];
return result;
}
//测试
phoneticLookup("charlie");