Reputation:
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 also
obj.index` (which shouldn't have worked for an array ).
Now I really am confused to what obj
exactly is....
Upvotes: 1
Views: 55
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:
Array.prototype
.length
.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.[]
).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