如何在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中的任何更多。你应该使用$ c>循环的迭代器和,通常 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}`);
}