如何在for循环周期内使用布尔标志?

时间:2019-07-01 15:04:11

标签: javascript jquery boolean flags

我想在满足特定条件(两个字符串彼此匹配)时调用一个函数(显示模式)。 条件发生变化并在for循环周期内设置(循环两个JSON文件的元素)。

可能的条件是三个:

1)没有键入字符串,没有匹配项,没有问题;

2)我输入一个字符串:for循环周期告诉我字符串不匹配;

3)我输入了一个字符串:for循环周期告诉我字符串匹配。

第二个和第三个条件是有问题的,因为它们在for循环周期内,因此我需要为每个条件调用一个特定的动作,避免在条件2)满足时对循环中的每个元素重复执行该动作满足。

我想设置一个布尔标志,但是我不确定我该如何使用它。 我在for循环外创建了一个变量,并将其值设置为“ false”。 在for循环中,我通过给变量赋值“ true”来调用它。 在第二个for循环之外,我在if语句内调用它,该语句调用一个函数来显示模式。

我编写了以下代码:

function validateCitta() {
    $("#cercaCitta").prop("disabled", false);        
    let text = $('#inlineFormInputCitta').val();
    if (text === "") {
        $("#errorLog").show();
    }
    else {   


        var check = false;    //  I set the flag variable 


        $.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++) {
                    let typeCity = data.features[i].properties.geocoding.type;
                    if (typeCity === "city") {
                        let nameCity = data.features[i].properties.geocoding.name;
                        for (let i = 0; i < json.tappe.length; i++) {
                            let tappa = json.tappe[i];
                            let city = json.tappe[i].city;
                            if (city === nameCity) {
                                console.log("JSON file has been activated");


                                check = true;  // the condition 3 is fulfilled, then I perform the action below:

                                $("#tbody").append("<tr><td>" + tappa.name + "</td><td>" + tappa.state + "</td><td>" + tappa.region + "</td><td>" + tappa.city + "</td></tr>");                                    
                            }    
                            else if (check){     // the condition 3 is false, the condition 2 is fullfilled, then I show the Modal:
                                $('#myModal').show();
                            }    
                            ;
                        }                           
                        ;
                    }
                }
            }
        })           
    }
};

哪种是设置和调用布尔标志的正确方法? 您能给我展示一些例子来更好地理解这种特定变量的用法以及从头开始和在一个周期内使用它的区别吗?

0 个答案:

没有答案