K
K
kavalorn1232018-03-05 14:14:55
JavaScript
kavalorn123, 2018-03-05 14:14:55

Why doesn't Array.forEach see the first argument?

regExSearch : function(searchString, name) {
    var separatedItem = name.toLowerCase().split(' ');
    var result;
    separatedItem.forEach(function(item) {
      var re = new RegExp("^" + searchString);
      result = re.test(item);
      if (result) return;
    });
    return result;
  },

The searchString contains the string "violently", the name string "Yaroslav Ivanovich"; the problem is that in the forich callback, the first argument throws a ReferenceError: item is not defined. What could be the problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2018-03-05
@kavalorn123

No errors, the given code works fine:
The logic suffers though - the line is if (result) return;meaningless - the function will be interrupted anyway. And result, most likely, should not be overwritten when the string does not match the regular expression (as a result, the function returns true for the strings ' Yaroslav ' and ' Ivan Yaroslavovich ', and false for ' Yaroslav Ivanovich ' ). In general, the whole code can be reduced to this:

function regExSearch(searchString, name) {
    var re = new RegExp("^" + searchString);
    var words = name.toLowerCase().split(' ');
    return !!words.find((item) => re.test(item));
}

Or even this (depending on how old browsers are in support):
function regExSearch(searchString, name) {
    var words = name.toLowerCase().split(' ');
    return !!words.find((item) => item.startsWith(searchString));
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question