var lemonadeChange = function(bills) {
let fiveCount = 0
let tenCount = 0
bills.forEach(element =>{
if(element === 5){
fiveCount += 1
}else if(element === 10){
if(fiveCount >= 1){
fiveCount -= 1
tenCount += 1
}else{
return false
}
}else if(element === 20){
if(tenCount >= 1 && fiveCount >=1){
tenCount -= 1
fiveCount -= 1
}else if(fiveCount >=3 ){
fiveCount -= 3
}else{
return false
}
}
})
return true
};
console.log(lemonadeChange([10,5])) //true
按照正常的逻辑,数组第一个数为10时,判断到elemetn为10且fiveCount < 1这时候应该直接返回false了,但程序已经在正常执行,等执行完了所有循环后执行了return true的代码所以得到的结果为true。
而是用for循环时
let fiveCount = 0
let tenCount = 0
for (let i = 0 ; i < bills.length ; i++){
if(bills[i] === 5){
fiveCount += 1
}else if(bills[i] === 10){
if(fiveCount >= 1){
fiveCount -= 1
tenCount += 1
}else{
return false
}
}else if(bills[i] === 20){
if(tenCount >= 1 && fiveCount >=1){
tenCount -= 1
fiveCount -= 1
}else if(fiveCount >=3 ){
fiveCount -= 3
}else{
return false
}
}
}
return true
当程序执行到return时就会打断后续的循环不再执行。
总结:foreach中不能通过return来打断循环