René Nyffenegger
René Nyffenegger

Reputation: 40543

Is object[0] sort of a default key for an object in JavaScript?

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".

Upvotes: 0

Views: 519

Answers (1)

inklesspen
inklesspen

Reputation: 1186

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'.)

Upvotes: 4

Related Questions