0

Here's a small JavaScript snippet:

  var re_words = /\w+/g;

  var words;
  while (words = re_words.exec(' here are a few (sic!) words ')) {
     alert(words);
  }

The loop alerts the words found in the input string, which is what I expected, because all the JavaScript tutorials tell me so.

Now, typeof(words) results in object.

Therefore, I would have expected alert(words) to give me object.

If I inspect the elements in words, I found them to be 0, "index" and "input". The element words[0] is the same as what is alerted with words.

So, the question is: is the element 0 sort of a default index for an Object in JavaScript which is returned if it is defined.

Or asked differently: why does alert(words) give the same effect as alert(words[0])? I would have expected alert(words) to give a "Object".

1 Answer 1

4

The result of executing a regexp is an Array, which is a special kind of Object. The array also has two properties, index and input. words[0] contains the matched characters. Calling .toString() on an array (as is implicitly done by alert()) joins the elements of the array with a comma (after calling .toString() on each of those). In this case, since there was only one element, the comma was superfluous, so the result of calling .toString() on the array is the same as the first element in the array.

(Not sure what browser you're using; in Firefox, alert(words) gives 'here', then 'are', and so on until finally it gives the string 'words'.)

Sign up to request clarification or add additional context in comments.

1 Comment

+1. words!==words[0] and ['a']!=='a', only their string representations are the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.