0

I have a blob of text like this, called body:

images: OK
default: OK
...

So I'm trying to work with it concisely, like so:

   for (str in body.split('\n')) {
       console.log(str);
   }

but I just get a list of numbers (the indices of each element). Why is this happening? Further more, I can't seem to do filter functions on this because of this behavior:

body.split('\n').filter(function(str){ return str && str.length > 0; });

just returns the whole array even if there are empty elements.

BrDaHa
  • 5,138
  • 5
  • 32
  • 47
  • 4
    `for-in` loops through the *property names* of an object, not their values. The linked question goes into some detail about how to loop through arrays and array-like things. – T.J. Crowder Jul 07 '16 at 16:24
  • Re the second part of your question: That code won't keep empty entries (https://jsfiddle.net/o6e2L1uu/), so apparently they aren't empty. (Also note that you don't need the `&& str.length > 0` part, `""` is falsy, and any other string is truthy.) You might throw a `trim` in (`return str.trim();`) in case they consist only of whitespace. – T.J. Crowder Jul 07 '16 at 16:25
  • Learned something new, thanks! – BrDaHa Jul 07 '16 at 16:48
  • Or more concisely, `body.split('\n').filter(Boolean)`. –  Jul 07 '16 at 18:44

0 Answers0