简体   繁体   中英

Javascript return behavior inside a forEach loop

Quick question about return behaviour inside a forEach loop using lodash.

The function should check if a string ends with a predefined array of unique prefixes and if yes, return the string with that prefix deleted.

When I call prefixParser('someString') it always returns ('someString') even if the if statement matches. Shouldn't the return inside the foreEach/if end the whole function?

Or am I missing something about the execution context?

prefixParser(str) {
        let value= str;

        this.prepostfix.forEach( prefix => {
            if(_.startsWith(value,prefix)){
                return _.trimStart(value, prefix);
            }
        });

        return value
    }

changing return to

value = _.trimStart(value, prefix)

solves the issue but i'd like to understand the mechanics here. Thanks!

If I am not mistaken, the arrow function only has an impact on the a functions binding, so your return in the forEach loop only exits the forEach function. Your prefixParser function continues to run until your return value.

Additionally, you are running your forEach function against the array defined in this.prepostfix, but to make the result available to the rest of your function, you need to assign it to a variable. Here is a simplified version of your function that should either assign the result of your forEach or default to the submitted string:

prefixParser(str) {
  let value = str;

  this.prepostfix.forEach(prefix => {
    if (_.startsWith(value, prefix)) {
      value = _.trimStart(value, prefix);
    }
  });

  return value
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM