functiongetDrink(type) { var fn; var drinks = { coke: function () { return'Coke'; }, pepsi: function () { return'Pepsi'; }, lemonade: function () { return'Lemonade'; }, default: function () { return'Default item'; } }; // if the drinks Object contains the type // passed in, let's use it if (drinks[type]) { fn = drinks[type]; } else { // otherwise we'll assign the default // also the same as drinks.default // it's just a little more consistent using square // bracket notation everywhere fn = drinks['default']; } return fn(); }
// called with "dr pepper" var drink = getDrink('dr pepper'); console.log(drink); // 'Default item'
我们可以简化上面的内容,if 并在表达式中 else 使用 or ||运算符:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
functiongetDrink(type) { var drinks = { coke: function () { return'Coke'; }, pepsi: function () { return'Pepsi'; }, lemonade: function () { return'Lemonade'; }, default: function () { return'Default item'; } }; return (drinks[type] || drinks['default'])(); }
functiongetDrink(type) { var drink; var drinks = { coke: function () { drink = 'Coke'; }, pepsi: function () { drink = 'Pepsi'; }, lemonade: function () { drink = 'Lemonade'; }, default: function () { drink = 'Default item'; } };
// invoke it (drinks[type] || drinks['default'])();
// return a String with chosen drink return'The drink I chose was ' + drink; }
var drink = getDrink('coke'); // The drink I chose was Coke console.log(drink);
这些是非常基本的解决方案,而 Object 字面量包含一个 function 返回 a 的值 String,在您只需要 a 的情况下 String,可以将 a String 用作键的值-在某些情况下,该函数将包含逻辑,该逻辑将从该函数返回。如果您要混合使用函数和字符串,则始终可以使用函数来保存查找 type 和调用(如果是函数)会更容易-我们不想尝试调用 String。
对象字面量“告吹”
对于 switch 案例,我们可以让它们失败(这意味着一个以上的案例可以应用于特定的代码段):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
var type = 'coke'; var snack; switch (type) { case'coke': case'pepsi': snack = 'Drink'; break; case'cookies': case'crisps': snack = 'Food'; break; default: drink = 'Unknown type!'; } console.log(snack); // 'Drink'