首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JS退出.map()函数

JS退出.map()函数
EN

Stack Overflow用户
提问于 2019-12-05 10:29:56
回答 2查看 7.5K关注 0票数 1

因此,我使用一个map函数来迭代和数组,并且在满足条件之后,我希望停止遍历映射函数中的元素。

是否有办法这样做?

例:

代码语言:javascript
复制
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的情况下使用

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-12-05 10:35:22

您不是在寻找.map函数,但您需要使用.some.find

代码语言:javascript
复制
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!")

票数 7
EN

Stack Overflow用户

发布于 2019-12-05 10:38:27

如果不需要索引,可以使用for...of循环:

代码语言:javascript
复制
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停止迭代的唯一方法是抛出一个异常。你可以这样做:

代码语言:javascript
复制
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!")

但这在任何方面都不会更好。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59193124

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档