2009-09-29 65 views
19
Ext.each(boundsExtend, function(value) 
{ 
    if(value != record.ID) break; 
}); 

那么如何打破或继续Ext.each循环?如何打破或继续Ext.each

+0

这是一个类似的例外,我得到的时候不这样做,并删除一个对象。因此itemId不在那里。 “Uncaught TypeError:无法读取属性'itemId'的undefined” – MacGyver 2014-03-27 23:28:50

回答

39

docs

If the supplied function returns false, iteration stops and this method returns the current index.

所以作为OP的例子(假设record是在范围和非空):

Ext.each(boundsExtend, function(value) { 
    if (value != record.ID) { 
    return false; 
    } 
    // other logic here if ids do match 
}); 

注意,返回false完全退出循环,所以在这种情况下,第一个不匹配的记录将绕过任何额外的检查。

但是,我猜你真的想要做的是循环直到你找到匹配的记录,做一些逻辑,然后短路循环。如果是这样的话,逻辑实际上是:

Ext.each(boundsExtend, function(value) { 
    if (value === record.ID) { 
    // do your match logic here... 
    // if we're done, exit the loop: 
    return false; 
    } 
    // no match, so keep looping (i.e. "continue") 
}); 

任何其他值是没有明确false(例如null默认)将继续循环下去。

+0

太棒了,但如何继续? – 2011-01-03 15:52:18

+20

返回但不为假。 – 2011-01-05 01:00:36

+0

耶我上调了布莱恩 – 2012-06-14 19:58:51

3
var countries = ['Vietnam', 'Singapore', 'United States', 'Russia']; 

Ext.Array.each(countries, function(name, index, countriesItSelf) { 
    console.log(name); 
}); 

Ext.Array.each(countries, function(name, index, countriesItSelf) { 
if (name === 'Singapore') { 
    return false; // break here 
} 
}); 
1

返回false为 '突破',并返回什么,但false为 '继续'。

var array = [1, 2, 3]; 
Ext.each(array, function(ele){ 
    console.log(ele); 
    if(ele !== 2){ 
     return false; // break out of `each` 
    } 
}) 

Ext.each(array, function(ele){ 
    console.log(ele); 
    if(ele !== 3){ 
     return true; // continue 
    } 
})