--- id: 56533eb9ac21ba0edf2244ca challengeType: 1 videoUrl: 'https://scrimba.com/c/cdBk8sM' forumTopicId: 18373 title: 使用对象进行查找 --- ## Description
对象和字典一样,可以用来存储键/值对。如果你的数据跟对象一样,你可以用对象来查找你想要的值,而不是使用switch或if/else语句。当你知道你的输入数据在某个范围时,这种查找方式极为有效。 这是简单的反向字母表: ```js var alpha = { 1:"Z", 2:"Y", 3:"X", 4:"W", ... 24:"C", 25:"B", 26:"A" }; alpha[2]; // "Y" alpha[24]; // "C" var value = 2; alpha[value]; // "Y" ```
## Instructions
把 switch 语句转化为lookup对象。使用它来查找val属性的值,并赋值给result变量。
## Tests
```yml tests: - text: phoneticLookup("alpha")应该等于"Adams"。 testString: assert(phoneticLookup("alpha") === 'Adams'); - text: phoneticLookup("bravo")应该等于"Boston"。 testString: assert(phoneticLookup("bravo") === 'Boston'); - text: phoneticLookup("charlie")应该等于"Chicago"。 testString: assert(phoneticLookup("charlie") === 'Chicago'); - text: phoneticLookup("delta")应该等于"Denver"。 testString: assert(phoneticLookup("delta") === 'Denver'); - text: phoneticLookup("echo")应该等于"Easy"。 testString: assert(phoneticLookup("echo") === 'Easy'); - text: phoneticLookup("foxtrot")应该等于"Frank"。 testString: assert(phoneticLookup("foxtrot") === 'Frank'); - text: phoneticLookup("")应该等于undefined。 testString: assert(typeof phoneticLookup("") === 'undefined'); - text: 请不要修改return语句。 testString: assert(code.match(/return\sresult;/)); - text: 请不要使用caseswitch,或if语句。 testString: assert(!/case|switch|if/g.test(code.replace(/([/]{2}.*)|([/][*][^/*]*[*][/])/g,''))); ```
## Challenge Seed
```js // Setup function phoneticLookup(val) { var result = ""; // Only change code below this line 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"; } // Only change code above this line return result; } // Change this value to test phoneticLookup("charlie"); ```
## Solution
```js function phoneticLookup(val) { var result = ""; var lookup = { alpha: "Adams", bravo: "Boston", charlie: "Chicago", delta: "Denver", echo: "Easy", foxtrot: "Frank" }; result = lookup[val]; return result; } ```