搜索数组并返回值

时间:2016-04-25 16:33:51

标签: javascript arrays multidimensional-array

我需要你的帮助,

标识'喜欢能够提出类似于下面的代码结构的javascript函数,除了我在编程方面不够强大以提出可行的解决方案。

我希望能够输入一个给定的值,然后,使用该值,搜索数组并返回值短名称(冒号字符右侧的值)

function test() {

var filenames = [
        "REQUEST FOR INFO":"REQI",
        "MEDIA CALL":"MC",
        "ISSUES NOTE":"ISN"
    ]

EX1.)

    var value_to_search_for = "REQUEST FOR INFO (ALPHA)"

    if (value_to_search_for matches the value in the array filenames) then {

        return "REQI"

    }

EX.2)
    var value_to_search_for = "MEDIA CALL"

    if (value_to_search_for matches value in the array filenames) then {

        return "MC"

    }

}

1 个答案:

答案 0 :(得分:1)

您可以将其更改为对象,然后您可以执行此操作



var filenames = {
  "REQUEST FOR INFO": "REQI",
  "MEDIA CALL": "MC",
  "ISSUES NOTE": "ISN"
};

var getValue = function(val, obj) {
  if (val in obj) return obj[val];
}

console.log(getValue('ISSUES NOTE', filenames));




您也可以将其更改为对象数组,然后就可以执行此操作



var filenames = [
  {"REQUEST FOR INFO": "REQI"},
  {"MEDIA CALL": "MC"},
  {"ISSUES NOTE": "ISN"}
];

var getValue = function(val, array) {
  array.forEach(function(el) {
    for (prop in el) {
      if (prop == val) console.log(el[prop]);
    }
  });
}

getValue('MEDIA CALL', filenames);