forEach can't continue to skip or break to terminate the loop, there is no return value, can't return
can be used to throw an exception (try catch) to terminate the foreach loop
example
This is a code that uses keywords to query text and returns words
let list = [
{
key:['什么价格','怎么卖','价格多少'],
call:'一瓶3元'
},
{
key:['卖的什么','什么商品','都有哪些东西'],
call:'我们卖汽水'
}
]
let text = '这个商品怎么卖?'
// 利用报错终止foreach,返回需要的返回词
try {
list.forEach(v=>{
v.key.forEach(i=>{
console.log(i);
if(text.indexOf('i')){
console.log(v.call);
throw new Error(v.call)
}
})
})
} catch (e) {
console.log(e.message);
}