0

我有一个格式如下的数组:

var markers = [
    ['Title', 15.102253, 38.0505243, 'Description', 1], 
    ['Another Title', 15.102253, 38.0505243, 'Another Description', 2],
    ['Title 3', 15.102253, 38.0505243, 'Description 3', 3], 
];

然后我将一个查询字符串传递给页面(m = 1,2),该页面以逗号分隔,然后拆分以创建如下所示的数组:

['1', '2']

我需要做的是找到 ID (markers[i][4]) 来自查询字符串的所有“标记”。

实现这一目标的最佳方法是什么?理想情况下,我想创建一个与“标记”格式相同的第三个数组,但只显示查询字符串的结果。

任何帮助将不胜感激。

谢谢

4

2 回答 2

2

一种选择是使用嵌套循环:

var markers = [
    ['Title', 15.102253, 38.0505243, 'Description', 1], 
    ['Another Title', 15.102253, 38.0505243, 'Another Description', 2],
    ['Title 3', 15.102253, 38.0505243, 'Description 3', 3], 
];
var search = ['1', '2'];
var result = [];

for (var i = 0; i < search.length; i++)
    for (var j = 0; j < markers.length; j++)
        if (search[i] == markers[j][4]) {
            result.push(markers[j]);
            break;
        }

console.log(result);

演示:http: //jsfiddle.net/3TERD/

于 2012-05-10T10:27:44.507 回答
2

你不能在这里使用嵌套循环吗?

var filteredMarkers = [];

for(var i = 0; i < markers.length; i++) {

    for(var j = 0; j < queryStringArray.length; j++) {

        // this might need to be changed as your markers has index 4 as a number whereas the queryString array appears to be strings.
        if(markers[i][4] === queryStringArray[j]) {

            filteredMarkers.push(markers[i]);
            break;

        }

    }

}
于 2012-05-10T10:29:53.677 回答