如何在ES6地图中中断/中断/停止? [英] How to interrupt/break/stop forEach in ES6 Map?

查看:322
本文介绍了如何在ES6地图中中断/中断/停止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一个很好的方法(除了使用JS异常)在ES6 Map对象中停止forEach循环( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach

Is there a nice way (except using JS exceptions) to stop forEach loop in ES6 Map object (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach )

从MDN提供的示例中,有一种方法可以在'bar'(跳过栏)上停止枚举:

From example provided on MDN - is there a way to stop enumeration on 'bar' (skip bar):

function logMapElements(value, key, map) {
    console.log(`m[${key}] = ${value}`);
}
new Map([['foo', 3], ['bar', {}], ['baz', undefined]]).forEach(logMapElements);

对于建议关闭此问题的人员:是的,它类似于有关Array的问题。 prototype.forEach。

但是与此同时是不同的:大部分建议的答案将不能用于ES6集和映射。只有抛出异常才会起作用,但我要求其他一些方法

For the people who suggest to close this question: yes, it is similar to the questions about Array.prototype.forEach.
But at the same time is different: most of the suggested answers won't work with ES6 set and map. Only throwing the exception will work, but I ask for some other ways

推荐答案

没有好的理由使用 forEach ES6中的任何更多。你应该使用循环的迭代器和,通常 break

There is no good reason to use forEach any more in ES6. You should use iterators and for … of loops from which you can ordinarily break:

const m = new Map([['foo', 3], ['bar', {}], ['baz', undefined]]);
for (let [value, key] of m) {
    console.log(`m[${key}] = ${value}`);
}

这篇关于如何在ES6地图中中断/中断/停止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆