因此,我使用一个map函数来迭代和数组,并且在满足条件之后,我希望停止遍历映射函数中的元素。
是否有办法这样做?
例:
var arr = [1,2,3,4,5,6,7,8,9,10];
arr.map((el,index)=>{
console.log("Element : ",el)
if(el > 5){
//Stop the map function and proceed to the next operation
//like goto line 11 so skip going trough the map anymore
console.log("Stop")
}
})
console.log("Sucess!")
所以在这个例子中,我只想在它里面的元素有一个大于5的值时停止这个映射。有什么方法可以用map来完成这个任务,还是我应该找到另一个解决方案呢?
为什么要映射?-Seems就像一个无止境的解决方案,我想知道是否可以在y的情况下使用
发布于 2019-12-05 10:35:22
您不是在寻找.map函数,但您需要使用.some或.find
var arr = [1,2,3,4,5,6,7,8,9,10];
arr.some((el,index)=>{
console.log("Element : ",el)
if(el > 5){
//Stop the map function and proceed to the next operation
//like goto:11
console.log("Stop")
return true // stop the iteration of the first "truty" value
}
return false
})
console.log("Sucess!")
发布于 2019-12-05 10:38:27
如果不需要索引,可以使用for...of循环:
var arr = [1,2,3,4,5,6,7,8,9,10];
for (const el of arr) {
console.log("Element : ",el)
if(el > 5){
//Stop the map function and proceed to the next operation
//like goto:11
console.log("Stop")
break;
}
}
console.log("Sucess!")
为什么映射?-Seems就像一个无止境的解决方案,我想知道是否可以在y的情况下使用
你也可以用螺丝刀用粗把手钉钉子,但它仍然是工作的错误工具;)
用.map停止迭代的唯一方法是抛出一个异常。你可以这样做:
var arr = [1,2,3,4,5,6,7,8,9,10];
var sentinel = {};
try {
arr.map((el,index)=>{
console.log("Element : ",el)
if(el > 5){
//Stop the map function and proceed to the next operation
//like goto line 11 so skip going trough the map anymore
console.log("Stop")
throw sentinel;
}
})
} catch(e) {
if (e !== sentinel) throw e;
}
console.log("Sucess!")
但这在任何方面都不会更好。
https://stackoverflow.com/questions/59193124
复制相似问题