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

我正在尝试比较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'

        }


BIG阳
浏览 213回答 2
2回答

小怪兽爱吃肉

您可以从timeline对象数组创建城镇名称数组,以便可以比较在时间轴中是否找到特定的城镇。这可以通过以下方式完成:使用Array.prototype.map()通过你的迭代timeline对象的数组,并返回所有的列表townshipname通过使用以下命令检查阵列中是否存在给定的乡镇 Array.prototype.indexOf()示例代码如下:// Generate an array of townships extract from timelinevar townships = timeline.map(function(item) {&nbsp; return item.townshipname;});// Attempt to search a given township in your generated arrayvar townshipIndex = townships.indexOf(event.feature.getProperty('township'));if (townshipIndex !== -1) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; var timepush = timeline[townshipIndex].timelinename;} else {&nbsp; &nbsp; var timepush = 'No Timeline Entered';}另外,您可以使用for...of循环并在找到匹配项后中断循环。我们假设没有输入任何时间轴作为“基本状态”,然后我们可以在找到匹配项后进行更新:var timepush = 'No Timeline Entered';for (var item of timeline) {&nbsp; if (item.townshipname === event.feature.getProperty('township')) {&nbsp; &nbsp; timepush = item.timelinename;&nbsp; &nbsp; break;&nbsp; }}如果您确实需要IE支持,那么我们可以使用经典for循环:var timepush = 'No Timeline Entered';for (var i = 0; i < timeline.length; i++) {&nbsp; if (timeline[i].townshipname === event.feature.getProperty('township')) {&nbsp; &nbsp; timepush = timeline[i].timelinename;&nbsp; &nbsp; break;&nbsp; }}

qq_笑_17

因此,有两种不同的方法可以实现此目的,如果您有一个索引对象数组,最快的方法是:for(var i = 0; i < timeline.length; i++){&nbsp; &nbsp; if(event.feature.getProperty('township') == timeline[i].townshipname){&nbsp; &nbsp; &nbsp; &nbsp; var timepush = timeline[i].timelinename;&nbsp; &nbsp; }}我可以很快提出另一个例子。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript