简体   繁体   English

object [0]是JavaScript中对象的默认键吗?

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

Here's a small JavaScript snippet: 这是一个小的JavaScript代码段:

  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. 循环会提醒输入字符串中找到的单词,这是我所期望的,因为所有JavaScript教程都告诉我。

Now, typeof(words) results in object . 现在, typeof(words)生成 object

Therefore, I would have expected alert(words) to give me object . 因此,我期望警报(单词)能给我object

If I inspect the elements in words, I found them to be 0, "index" and "input". 如果我检查单词中的元素,我发现它们分别为0,“索引”和“输入”。 The element words[0] is the same as what is alerted with words. 元素单词[0]与单词警告相同。

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. 因此,问题是:元素0是JavaScript中Object的默认索引的一种,如果已定义则返回该索引。

Or asked differently: why does alert(words) give the same effect as alert(words[0]) ? 或以不同的方式问:为什么alert(words)alert(words [0])具有相同的效果? I would have expected alert(words) to give a "Object". 我本来希望alert(words)给出一个“对象”。

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. word [0]包含匹配的字符。 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). 在数组上调用.toString() (由alert()隐式完成)使数组的元素带有逗号(在每个数组上调用.toString()之后)。 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. 在这种情况下,由于只有一个元素,所以逗号是多余的,因此在数组上调用.toString()的结果与数组中的第一个元素相同。

(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' .) (不确定使用的浏览器;在Firefox中, alert(words)给出'here' ,然后是'are' ,依此类推,直到最后给出字符串'words' 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM