Javascript中的数组搜索不起作用

时间:2015-10-08 03:21:24

标签: javascript arrays json loops

我有以下数据结构:

var map_neighbours = [{
    "Alaska": ["UstKamchatsk", "Yukon"]
}, {
    "Algeria": ["Chad", "Egypt", "SierraLeone", "Spain"]
}, {
    "AntarticWildlifeTerritory": ["AustralianAntarticTerritory", "SouthAfricanAntarticTerritory"]
}, .....]

用户通过页面选择一个区域,我想遍历这个结构,找到区域,然后循环遍历子区域(在相应的位置)。

例如,对于Algeria,我想逐个循环地获取"Chad", "Egypt", "SierraLeone", "Spain"

我尝试了一些不成功的变体(region由用户提供,如上所述):

var neighbourArray = map_neighbours[region];

$.each(neighbourArray, function(idx, val) {

    console.log("Neighbours= " + neighbourArray[region][idx]);

});

$.each(map_neighbours, function(outer, val) {

    if (map_neighbours[outer] == region) {

        neighbourArray = (map_neighbours[outer][]);

        $.each(neighbourArray, function(inner, val) {

            console.log("Neighbours= " + neighbourArray[outer][inner]);

        });

     );

};

感谢您的任何建议。

1 个答案:

答案 0 :(得分:2)

使用当前结构,您需要迭代数组并查看该项是否具有输入值作为键



var map_neighbours = [{
  "Alaska": ["UstKamchatsk", "Yukon"]
}, {
  "Algeria": ["Chad", "Egypt", "SierraLeone", "Spain"]
}, {
  "AntarticWildlifeTerritory": ["AustralianAntarticTerritory", "SouthAfricanAntarticTerritory"]
}];

var input = 'Algeria',
  result;
$.each(map_neighbours, function(i, item) {
  if (item[input]) {
    result = item[input];
    return false;
  }
})

if (result) {
  snippet.log(JSON.stringify(result));
} else {
  snippet.log('not found')
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
&#13;
&#13;
&#13;

但处理这种情况的更好的结构是使用键值对象而不是对象数组

&#13;
&#13;
var map_neighbours = {
  "Alaska": ["UstKamchatsk", "Yukon"],
  "Algeria": ["Chad", "Egypt", "SierraLeone", "Spain"],
  "AntarticWildlifeTerritory": ["AustralianAntarticTerritory", "SouthAfricanAntarticTerritory"]
};

var input = 'Algeria',
  result = map_neighbours[input];

if (result) {
  snippet.log(JSON.stringify(result));
} else {
  snippet.log('not found')
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
&#13;
&#13;
&#13;