How to early break reduce() method?

后端 未结 12 1211
忘掉有多难
忘掉有多难 2020-11-28 05:44

How can I break the iteration of reduce() method?

for:

for (var i = Things.length - 1; i >= 0; i--) {
  if(Things[i] <=         


        
12条回答
  •  醉酒成梦
    2020-11-28 06:43

    You can break every code - and thus every build in iterator - by throwing an exception:

    function breakReduceException(value) {
        this.value = value
    }
    
    try {
        Things.reduce(function(memo, current) {
            ...
            if (current <= 0) throw new breakReduceException(memo)
            ...
        }, 0)
    } catch (e) {
        if (e instanceof breakReduceException) var memo = e.value
        else throw e
    }
    

提交回复
热议问题