user10014964
user10014964

Reputation:

Why is this showing both array and object like behaviour

Please consider the below javaScript code.

var obj = /e/.exec("The best things in life are free!");
var k = "";
var x;
for (x in obj) {
  k = k + " " + obj[x] + " " + x + "<br>";
}
document.getElementById("demo").innerHTML = (obj instanceof Array) + " " + obj[0] + " " + obj[1] + " " + obj.index + "<br>" + k;
<h2>JavaScript Regular Expressions</h2>
<p id="demo"></p>

Gives an output

JavaScript Regular Expressions
true e undefined 2
e 0
2 index
The best things in life are free! input
undefined groups  

Now in the above code I used obj[0]obj[1](which are array only notations), and alsoobj.index` (which shouldn't have worked for an array ).

Now I really am confused to what obj exactly is....

Upvotes: 1

Views: 55

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075019

Now in the above code I used obj[0] , obj1 (which are array only notations)

No, they aren't. For instance:

const obj = {answer: 42, 42: "is the answer"};
const str = "answer";
console.log(obj[str]); // 42
console.log(obj[42]);  // is the answer

.... and also obj.index (which shouldn't have worked for an array )

Yes, they should. :-)

Standard arrays in javaScript aren't really arrays at all. They're just objects that:

  • Inherit from Array.prototype.
  • Have special behavior for a property named length.
  • Have special behavior for properties with names that match the definition of an array index (a string that, when converted to a number n, is in the range 0 <= n < 232 - 1). These are the properties that correspond to the array entries. We generally write them without quotes (myArray[0]), but officially they are strings.
  • Have their own literal form ([]).

Since they're objects, they can have properties as well:

const a = [1, 2, 3];
a.answer = 42;
console.log(a.answer); // 42

JavaScript itself makes use of this fact in a couple of places (but not many), including the RegExp.prototype.exec function as you discovered. Another place is in the first argument passed to a tag function, which has entries for the string segments from the template and a raw property with the raw version of those segments.

More on my anemic little blog: A Myth of Arrays

Upvotes: 3

Related Questions