2020-09-29 22:09:05 +02:00

3.2 KiB
Raw Blame History

id, title, challengeType, videoUrl, forumTopicId, localeTitle
id title challengeType videoUrl forumTopicId localeTitle
56533eb9ac21ba0edf2244ca Using Objects for Lookups 1 https://scrimba.com/c/cdBk8sM 18373 使用对象进行查找

Description

对象和字典一样,可以用来存储键/值对。如果你的数据跟对象一样你可以用对象来查找你想要的值而不是使用switch或if/else语句。当你知道你的输入数据在某个范围时这种查找方式极为有效。 这是简单的反向字母表:
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

tests:
  - text: <code>phoneticLookup("alpha")</code>应该等于<code>"Adams"</code>。
    testString: assert(phoneticLookup("alpha") === 'Adams');
  - text: <code>phoneticLookup("bravo")</code>应该等于<code>"Boston"</code>。
    testString: assert(phoneticLookup("bravo") === 'Boston');
  - text: <code>phoneticLookup("charlie")</code>应该等于<code>"Chicago"</code>。
    testString: assert(phoneticLookup("charlie") === 'Chicago');
  - text: <code>phoneticLookup("delta")</code>应该等于<code>"Denver"</code>。
    testString: assert(phoneticLookup("delta") === 'Denver');
  - text: <code>phoneticLookup("echo")</code>应该等于<code>"Easy"</code>。
    testString: assert(phoneticLookup("echo") === 'Easy');
  - text: <code>phoneticLookup("foxtrot")</code>应该等于<code>"Frank"</code>。
    testString: assert(phoneticLookup("foxtrot") === 'Frank');
  - text: <code>phoneticLookup("")</code>应该等于<code>undefined</code>。
    testString: assert(typeof phoneticLookup("") === 'undefined');
  - text: 请不要修改<code>return</code>语句。
    testString: assert(code.match(/return\sresult;/));
  - text: 请不要使用<code>case</code><code>switch</code>,或<code>if</code>语句。
    testString: assert(!/case|switch|if/g.test(code.replace(/([/]{2}.*)|([/][*][^/*]*[*][/])/g,'')));

Challenge Seed

// 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

function phoneticLookup(val) {
  var result = "";

  var lookup = {
    alpha: "Adams",
    bravo: "Boston",
    charlie: "Chicago",
    delta: "Denver",
    echo: "Easy",
    foxtrot: "Frank"
  };

  result = lookup[val];

  return result;
}