【问题标题】:Can you loop through an array of strings and match their value to keys in object dictionary?你能遍历一个字符串数组并将它们的值与对象字典中的键匹配吗?
【发布时间】:2014-07-16 04:36:21
【问题描述】:

例如,我希望输入的字符串“cab”返回“Clown Ace Boss”。

    var wiseBacronyms = function(initialInput) {
      initialInput = initialInput.toLowerCase();
      var dictionary = {"a":"Ace","b":"Boss","c":"Clown"};
      var letterArray = initialInput.split('');
      var result = [];

      for (var index = 0; index < letterArray.length; index++) {
        result.push(dictionary[index]);
      };
      return result.join('');
    };

【问题讨论】:

  • var dictionary = {"a":"Ace","b":Boss,"c":"小丑"};不正确,应该是数组字面量...
  • 老板应该是“老板”,但我仍然收到错误
  • @C-linkNepal 不,这样没关系,问题是它应该看起来像result.push(dictionary[letterArray[index]]);
  • @C-linkNepal:再想一想。它一个对象文字,一切都很好。
  • “你能遍历一个字符串数组并将它们的值与对象字典中的键匹配吗?” 是的,你可以。您的解决方案有什么问题? “但我仍然收到错误”如果您与我们分享,也许我们可以为您提供更好的帮助。

标签: javascript arrays string object for-loop


【解决方案1】:

您不想从字典中提取index,而是提取letterArray[index]

function wiseBacronyms(initialInput) {
  initialInput = initialInput.toLowerCase();
  var dictionary = {"a":"Ace","b":"Boss","c":"Clown"};
  var letterArray = initialInput.split('');
  var result = [];

  for (var index = 0; index < letterArray.length; index++) {
    result.push(dictionary[letterArray[index]]);
  };
  return result.join(' '); // also I added a space here
}

wiseBacronyms("cab") // "Clown Ace Boss"

【讨论】:

  • 当然整个函数可以缩短为function wiseBacronyms(initialInput) { var dictionary = {"a":"Ace","b":"Boss","c":"Clown"}; return initialInput.toLowerCase().split('').map(function(letter) { return dictionary[letter]; }).join(' '); }
  • 哦,是的!你是对的,但仍然只是索引无助于思考价值而不是关键......
【解决方案2】:

您想要访问letterArray 中每个项目的属性并将它们添加到您的result 数组中,最后使用join(' ') 来创建您的字符串。像这样:

var wiseBacronyms = function(initialInput) {
    initialInput = initialInput.toLowerCase();
    var dictionary = {"a":"Ace","b":"Boss","c":"Clown"};
    var letterArray = initialInput.split('');
    var result = [];

    letterArray.forEach(function(l) {
        result.push(dictionary[l]);
    });

    return result.join(' ');
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-08
    • 1970-01-01
    • 2019-05-27
    • 2015-07-13
    • 1970-01-01
    相关资源
    最近更新 更多