简体   繁体   English

如何检查 item 是否是循环中满足特定条件的最后一个元素

[英]How to check if item is the last element to fulfil a certain condition inside a loop

let's say I have arbitrary data which looks like this假设我有看起来像这样的任意数据

data= [{foo: bar},{foo: false},{foo:bar},{foo: false}];

and I am looping through that data using JQUERY.我正在使用 JQUERY 遍历该数据。 How do I check if an iteration is the last to fulfil a certain condition, for example;例如,如何检查迭代是否是最后一个满足特定条件的迭代;

$.each(data, function(key, value){


    if (value.foo===bar) {
        //do something
        // if this is the last which has a foo which is === bar then do something
    }

});

You can simulate a map + filter using reduce to do this:您可以使用reduce来模拟map + filter来做到这一点:

 var data = [{foo : 'bar'}, {foo : false}, {foo : 'bar'}, {foo : false}]; var elems = data.reduce(function(filtered, obj, index) { if (obj.foo === 'bar') { filtered.push(index); } return filtered; }, []); var last_index = elems[elems.length - 1]; data.forEach((value, index) => { if (value.foo === 'bar') { //do something //if this is the last which has a foo which is === bar then do something if (index === last_index) { // do the thing console.log('last: ', value, index); } } });

Or, you can work with data backwards, and use a boolean to detect whether you have seen the last element or not:或者,您可以向后处理data ,并使用布尔值来检测您是否看到了最后一个元素:

 var data = [{foo : 'bar'}, {foo : false}, {foo : 'bar'}, {foo : false}]; var last = true; $.each(data.reverse(), function(key, value) { if (value.foo === 'bar') { //do something //if this is the last which has a foo which is === bar then do something if (last) { // do the thing console.log('last: ', value, data.length - key - 1); last = false; } } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Use a regular for loop and iterate in reverse order over your collection so the first match would be the last match in original order使用常规for循环并以相反的顺序遍历您的集合,以便第一个匹配项将是原始顺序中的最后一个匹配项

 let data = [{ foo: 'bar' }, { foo: false }, { foo: 'bar' }, { foo: false }]; for (let i = data.length - 1, found = false; i >= 0; i--) { if (!found && data[i].foo === 'bar') { console.log('"last" match at ', i); found = true; } // ... }

you can store the last foo which is equal to bar in a variable and do operation on it outside the loop.您可以将最后一个等于 bar 的 foo 存储在一个变量中,并在循环外对其进行操作。

See below sample code请参阅下面的示例代码

var lastFooEqBar= null;
$.each(data.reverse(), function(key, value) {
    if (value.foo === bar) {
        //do something
        //store in variable
        lastFooEqBar = value;
    }
});
if(null!=lastFooEqBar) {
  //do operation on last foo equals to bar
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM