【问题标题】:How to exclude all the elements except than one within a for loop?如何在for循环中排除除一个之外的所有元素?
【发布时间】:2019-07-16 13:49:38
【问题描述】:

我设置了一个动态 Ajax 调用来比较在文本字段中键入的字符串(即城市名称)和 JSON 数组中的子键“type”的值。

我正在循环此类数组的元素以检查键“类型”的值。 我想在搜索结果中包含键“type”的值等于“city”的元素和键“type”的值等于“hamlet”的元素。

因为有些城市同时使用它们进行索引(即:JSON 数组的某些元素的“type”值等于“city”,而另一些元素的“type”值等于“hamlet” ),我想避免这些城市被多次索引/重复。

更准确地说,ajax 调用如下:

$.ajax({
  url: "https://nominatim.openstreetmap.org/search?q=" + encodeURIComponent($("#inlineFormInputCitta").val()) + "&format=geocodejson",
  dataType: "json",

  success: function(data) {
    var check = false;
    for (let i = 0; i < data.features.length; i++) {
      let typeCity = data.features[i].properties.geocoding.type;
      if (typeCity === "city") {
        let nameCity = data.features[i].properties.geocoding.name;
        for (let i = 0; i < francigena.tappe.length; i++) {
          let tappa = francigena.tappe[i];
          let city = francigena.tappe[i].city;
          let fs = francigena.tappe[i].fs;

          if (city === nameCity && fs === "true") {
            check = true;
            $('#tabellaEconteuti').show();

          } else if (city === nameCity) {
            check = true;
            console.log("JSON file has been activated");
            $('#tabellaEconteuti').show();

            $("#tbody").append("<tr><td>" + tappa.name + "</td><td>" + tappa.state + "</td><td>" + tappa.region + "</td><td>" + tappa.city + "</td></tr>");
            $("#tabella").show();
          }
        };
      };
    }


    if (
      !check
    ) {
      $('#myModal').modal('show');
    }
  },
}

我在这里做的是一个动态调用,将输入表单中键入的字符串与 API 调用中 url 中包含的字符串相关联:

url: "https://nominatim.openstreetmap.org/search?q=" + encodeURIComponent($("#inlineFormInputCitta").val()) + "&format=geocodejson",

然后我写了if (typeCity === "city") { //some function here}

当满足以下条件时,我想编写相同的函数:

if (typeCity === "hamlet")

但问题如下:

即城市“卢卡既有

"type": "city",

"type": "hamlet",

因此,for loop 循环数组中的所有元素,城市 Lucca 在我网页的搜索结果中显示了两次:第一次是因为“type”等于“city”;第二个,因为“type”等于“hamlet”。

我想写两个for loop函数,第一个包含来自typeCity : "hamlet"的结果;第二个包含包含“类型”:“城市”但不包含"typeCity" : "hamlet"的结果。因此,同时拥有两者的城市只会显示一次。

如何排除 for loop 函数中除一个以外的所有元素?或者有没有其他方法可以达到目的?

      • -E D I T - - - - ->

我正在尝试使用 Set() 方法解决问题:

success: function(data) {
    var check = false;
    var cityList = new Set()
    for (let i = 0; i < data.features.length; i++) {
        let typeCity = data.features[i].properties.geocoding.type;
        if (typeCity === "hamlet") {
            let nameCity = data.features[i].properties.geocoding.name;
            for (let i = 0; i < francigena.tappe.length; i++) {
                let tappa = francigena.tappe[i];
                let city = francigena.tappe[i].city;
                let fs = francigena.tappe[i].fs;
                if (city === nameCity && fs === "true") {
                    check = true;
                    console.log(" 'fs' === 'true' has been activated");
                    $('#tabellaEconteuti').show();

                    $("#tabella").show();

                } else if (city === nameCity) {
                    check = true;
                    console.log("JSON file has been activated");
                    $('#tabellaEconteuti').show();

                }
                if (cityList.has(city)) {
                    continue
                }
                cityList.add(city);
                if (typeCity === "city") {
                    let tappa = francigena.tappe[i];
                    let city = francigena.tappe[i].city;
                    let fs = francigena.tappe[i].fs;
                    if (city === nameCity && fs === "true") {
                        check = true;
                        console.log(" 'fs' === 'true' has been activated");
                        $('#tabellaEconteuti').show();

                        $('#TrenitaliaButton').on('click', showTrenitaliaInfo);

                    } else if (city === nameCity) {
                        check = true;
                        console.log("JSON file has been activated");
                        $('#tabellaEconteuti').show();
                    }
                }
            }
        } {
            {
                let nameCity = data.features[i].properties.geocoding.name;
                for (let i = 0; i < francigena.tappe.length; i++) {
                    let tappa = francigena.tappe[i];
                    let city = francigena.tappe[i].city;
                    let fs = francigena.tappe[i].fs;
                    if (city === nameCity && fs === "true") {
                        check = true;
                        console.log(" 'fs' === 'true' has been activated");
                        $('#tabellaEconteuti').show();


                    } else if (city === nameCity) {
                        check = true;
                        console.log("JSON file has been activated");

                        $('#tabellaEconteuti').show();

                    }
                };
            }
        };
    }
    if (
        !check
    ) {
        $('#tabellaEconteuti').hide();
    }
},

它不起作用,因为显示的城市是预期的八倍。 我应该如何改用Set() 方法?

    • -E D I T - - - -

我想我应该改变方法:而不是使用var cityList = new Set() 我想做以下事情:

1) 检查“type”的值是否为“city”;如果我发现它可能会设置一个变量 A 来表示我找到了它。

2) 接下来,我写第二个for loop 来检查“type”的值是否是“hamlet”。

我想这可能是正确的方法,因为它似乎是完成任务的一种更简单的方法。 我该如何设置这样的变量A?

【问题讨论】:

  • 在您的第一个循环中,保留一个包含所有通过其他测试的名称的数组。在第二个循环中,检查当前名称是否已经在名称数组中。如果您不想要具有相同名称的重复项,这将是解决方案。我理解正确吗?
  • @Wimanicesir 我应该创建一个新的 var 数组吗?
  • "城市卢卡显示两次" - 没有。那只是两个不同的城市,你当然想同时展示它们?
  • 图像中显示的示例显示了两个不同的城市。可能 API 已经返回了唯一的城市,你只是误解了结果。
  • @Wimanicesir 我编辑了我的问题(见最后的编辑),你的意思是什么?

标签: javascript json for-loop cycle


【解决方案1】:

在这里,Set 将是比 Array 更合适的选择。对于每个城市,检查它是否已经存在于 cityList 中。如果存在则继续下一个城市,否则添加到 cityList 并继续代码。

对另一个数组做同样的检查。

var check = false; 
var cityList = new Set()
for (let i = 0; i < data.features.length; i++) {
    let typeCity = data.features[i].properties.geocoding.type;
    if (typeCity === "city") {
        let nameCity = data.features[i].properties.geocoding.name;
        for (let i = 0; i < francigena.tappe.length; i++) {
            let tappa = francigena.tappe[i];
            let city = francigena.tappe[i].city;
            let fs = francigena.tappe[i].fs;

            if (cityList.has(city)) {
                continue;
            }
            cityList.add(city);

            if (city === nameCity && fs === "true") {
                check = true;                                       
                $('#tabellaEconteuti').show(); 

            } else if (city === nameCity) {
                check = true;
                console.log("JSON file has been activated");                                       
                $('#tabellaEconteuti').show();

                $("#tbody").append("<tr><td>" + tappa.name + "</td><td>" + tappa.state + "</td><td>" + tappa.region + "</td><td>" + tappa.city + "</td></tr>");    
                $("#tabella").show();                                        
            }
        }
    }
}

【讨论】:

    【解决方案2】:

    我通过设置布尔变量locationFoundbreak语句跳出循环解决了这个问题。

    首先,我在for loop 循环之外和之前将变量默认设置为false。 其次,我运行 for 循环,并在其中将变量设置为 true。执行了一些操作,然后我设置了一个break 语句以在找到值后跳出循环。

    然后我将变量设置为 false 作为if statementfor loop 之外的条件。执行了一些操作,然后我设置另一个 break 语句以在找到值后跳出循环。 它有效:所有结果都按预期显示且没有重复:

    $.ajax({
            url: "https://nominatim.openstreetmap.org/search?q=" + encodeURIComponent($("#inlineFormInputCitta").val()) + "&format=geocodejson",
            dataType: "json",            
    
            success: function (data) {                
    
                for (let i = 0; i < data.features.length; i++) {
    
                    var locationFound = false; //I set the boolean variable as false by default
                    let typeCity = data.features[i].properties.geocoding.type;
    
                    if (typeCity === "city") {
                        locationFound = true;  //here the boolean variable is true and an action is performed
    
                        break;    // I jump out of the loop
                        }
    
                    else if (locationFound === false) {
                        if (typeCity === "hamlet") {
                            var locationFound = true; //the boolean variable becomes true and the actions below are performed
                            //show the table
                            break;   //I jump out of the loop                         
                        }
                    }
    

    【讨论】:

      猜你喜欢
      • 2017-07-06
      • 1970-01-01
      • 1970-01-01
      • 2017-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多