这段代码有效,但是在数组中使用Item === CheckId时,会给出所有情况的结果。如何只获得最后一次? (Item === CheckId).length导致未定义。我也尝试在if语句之外创建变量,并在if语句内部增加变量。但是它只增加了一次。

        function updateDirections() {

                    $('.ui-selected').each(function(i, obj) {
                        textArea = $("#fname").val();
                        textArea = textArea.split(';');
                        //textArea.replace(/\(.+?,\ \{/, "");
                        //console.log((textArea[4].toLowerCase().indexOf(this.id) >= 0));
                        //textArea = textArea.map(function(w){ return +!!~this.id.indexOf(w) });
                        //console.log(obj.id);

                        Item = this.id;
                        var arrayLength = textArea.length;
                        for (var i = 0; i < arrayLength; i++) {
                            CheckId = textArea[i];
                            CheckId = CheckId.match(/\(.+?,\ \{/)
                            CheckId = String(CheckId).replace(/\(/g, "").replace(/,/g, "").replace(/ /g, "").replace(/\{/g, "");

                            if (Item === CheckId) {
                                console.log(textArea[i]);
                            }

                        }


                    });
                }

最佳答案

我不确定要实现的目标,但是如果要获取最后一个console.log的值,则可以使用变量:

Item = this.id;
var arrayLength = textArea.length,
    lastValue = null; // here is the variable
for (var i = 0; i < arrayLength; i++) {
    CheckId = textArea[i];
    CheckId = CheckId.match(/\(.+?,\ \{/)
    CheckId = String(CheckId).replace(/\(/g, "").replace(/,/g, "").replace(/ /g, "").replace(/\{/g, "");

    if (Item === CheckId) {
        lastValue = textArea[i];
    }

}
// do anything you want with lastValue

关于javascript - for循环的最后一次迭代if(某物等于某物),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41000678/

10-12 04:13