如何将变量与对象数组中的另一个变量进行比较?

时间:2019-04-08 21:19:11

标签: javascript

我正在尝试比较if中我的时间轴数组中的event.feature.getProperty('township')与timeline.townshipname。现在用[0]检查一个就可以了,但是我有一整列要检查。最好的方法是什么?

    //Load Timelines
    var timeline = [];
    jQuery.getJSON(timelines, function(data) {
        var entry = data.feed.entry;
        jQuery(entry).each(function(){
            var townshipname = this.gsx$township.$t;
            var timelinename = this.gsx$timeline.$t;
            var combined = {townshipname, timelinename};
            timeline.push(combined);
        });
    }); 
    // Output from timeline looks like
    // 0: {townshipname: "West Quincy", timelinename: "Ready for drops"}
    // 1: {townshipname: "Woodgate", timelinename: "Ready"}

    //Add infowindow to identify townships
    township_layer.addListener('click', function(event) {
        if (event.feature.getProperty('township') == timeline[0].townshipname){         
            var timepush = timeline[0].timelinename
        } else {
            var timepush = 'No Timeline Entered'
        }

2 个答案:

答案 0 :(得分:1)

您可以从timeline对象数组中创建城镇名称数组,以便可以比较是否在时间轴中找到了特定的城镇。

这可以通过以下方式完成:

  1. 使用Array.prototype.map()遍历对象timeline并返回所有townshipname的列表
  2. 使用Array.prototype.indexOf()
  3. 检查数组中是否存在给定的乡镇

示例代码如下:

// Generate an array of townships extract from timeline
var townships = timeline.map(function(item) {
  return item.townshipname;
});

// Attempt to search a given township in your generated array
var townshipIndex = townships.indexOf(event.feature.getProperty('township'));

if (townshipIndex !== -1) {         
    var timepush = timeline[townshipIndex].timelinename;
} else {
    var timepush = 'No Timeline Entered';
}

或者,您可以使用for...of loop并在找到匹配项后中断它。我们假设没有输入任何时间轴作为“基本状态”,然后我们可以在找到匹配项后进行更新:

var timepush = 'No Timeline Entered';
for (var item of timeline) {
  if (item.townshipname === event.feature.getProperty('township')) {
    timepush = item.timelinename;
    break;
  }
}

如果您确实需要IE支持,那么我们可以使用经典的for循环:

var timepush = 'No Timeline Entered';
for (var i = 0; i < timeline.length; i++) {
  if (timeline[i].townshipname === event.feature.getProperty('township')) {
    timepush = timeline[i].timelinename;
    break;
  }
}

答案 1 :(得分:0)

因此,有两种不同的方法可以实现此目的,如果您有一个索引对象数组,最快的方法是:

for(var i = 0; i < timeline.length; i++){
    if(event.feature.getProperty('township') == timeline[i].townshipname){
        var timepush = timeline[i].timelinename;
    }
}

我可以很快提出另一个例子。