-1

I'm playing around with PEG.js.

This is my grammar:

start = expression

expression = a:[a-z]+
{return a.join("");}

When I execute it in my browser:

obj = parser.parse("test");
for (var i = 0; i <= obj.length; i++) {
    console.log(i + " - " + obj[i])
}

I get this output:

0 - t
1 - e
2 - s
3 - t
4 - undefined

Why isn't it joined to only 1 word, even though I used return a.join("") in my grammar?

Evgenij Reznik
  • 17,916
  • 39
  • 104
  • 181
  • 5
    Best guess: `parser.parse()` returns a string. What is the loop supposed to do? – JJJ Oct 31 '15 at 18:53

2 Answers2

1

parser.parse does return the single word "test"; you are just printing it one character at a time.

Did you mean to do this?

var result = parser.parse("test");
console.log(result) // "test"
joews
  • 29,767
  • 10
  • 79
  • 91
1

To directly answer your question, you're getting one letter each iteration because a string acts like an array. So you're accessing one letter at a time by using obj[i] Try this to get one word returned.

obj = parser.parse("test");
for (var i = 0; i <= obj.length; i++) {
    console.log(i + " - " + obj)
}
Steve Perry
  • 556
  • 4
  • 11