I have seen this a few times in a few node examples but am never quite sure what to make of it. One example is with a net.Socket
. Here is a socket after a warning has been emitted from data listeners.
> commands._events.data
[ [Function], warned: true ];
Another example is in using /^(some)(regex)$/.exec("someregex")
[ 'someregex',
'some',
'regex',
index: 0,
input: 'someregex' ]
I'm not sure I understand what this data structure is. Is it a list or a dictionary? Why does it have indexes, and also key value pairs? I can do match.index
, but also match[1]
. How is it constructed?
(sorry if this is a dupe, couldn't find it in google).
It is an array, but with additional properties. The example with the regular expression can be explained from the specification for exec
- see steps 13 and 15 for instance where it creates an array, then adds the index
property:
- Let A be a new array created as if by the expression new Array() where Array is the standard built-in constructor with that name.
- Let matchIndex be i.
- Call the [[DefineOwnProperty]] internal method of A with arguments "index", Property Descriptor {[[Value]]: matchIndex, [[Writable]: true, [[Enumerable]]: true, [[Configurable]]: true}, and true.
(A is the eventual return value)
You can do the same:
var x = [1, 2, 3];
x['abc'] = 5;
console.log(x); //[1, 2, 3, abc: 5]
console.log(x.length); //3
console.log(x[1]); //2
console.log(x.abc); //5
In JavaScript everything that is not a primitive is an object.
Arrays are also objects in JavaScript. They have special functions and properties that make them behave as a collection but all the rules of objects still apply to them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With