Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this data structure that appears as a list, but has key value pairs?

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

like image 518
corvid Avatar asked Oct 23 '15 14:10

corvid


2 Answers

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:

  1. 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.
  2. Let matchIndex be i.
  3. 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
like image 183
James Thorpe Avatar answered Oct 23 '22 18:10

James Thorpe


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.

like image 25
OrangeKing89 Avatar answered Oct 23 '22 18:10

OrangeKing89