我正在尝试比较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'
}
答案 0 :(得分:1)
您可以从timeline
对象数组中创建城镇名称数组,以便可以比较是否在时间轴中找到了特定的城镇。
这可以通过以下方式完成:
Array.prototype.map()
遍历对象timeline
并返回所有townshipname
的列表Array.prototype.indexOf()
示例代码如下:
// 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;
}
}
我可以很快提出另一个例子。