javascript - How to interruptbreakstop forEach in ES6 Map? - Stack Overflow

admin2025-03-30  8

Is there a nice way (except using JS exceptions) to stop forEach loop in ES6 Map object ( )

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);

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

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

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);

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

Share Improve this question edited Mar 10, 2017 at 22:57 vmg asked Mar 10, 2017 at 21:41 vmgvmg 10.6k15 gold badges66 silver badges90 bronze badges 1
  • It is similar, but at the same time is different. Most of suggested answers won't work with ES6 set and map. Only throwing the exception will work, but I ask for some other ways. – vmg Commented Mar 10, 2017 at 22:56
Add a ment  | 

2 Answers 2

Reset to default 11

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 [key, value] of m) {
    console.log(`m[${key}] = ${value}`);
}

For those who don't want for-of, the following approach can be applied:

const length = myMap.size;
const iterator = myMap.entries();
for (let i = 0; i < length; i++) {
  const item = iterator.next().value;
  console.log(`myMap[${itemkey}] = ${value}`);
}

A benefit that I have personally encountered is that this approach produces less code during es5 transpilation (using Typescript transpiler with all its __values and __read definitions)...

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1743327922a212997.html

最新回复(0)