1

I was playing around with regex in JS today and came across a data structure I've never seen before: an array where some of the entries have keys. A method which returns such a data structure is the regex match function. Here's an example:

    var re = /SESSID=\w+=;/;
    var test = 'SESSID=aaaa=;fjsdfjd';
    var arr = test.match(re);
    console.log(arr);  // ["SESSID=aaaa=;", index: 0, input: "SESSID=aaaa=;fjsdfjd"]
    console.log(arr[0]);  // SESSID=aaaa=;
    console.log(arr['index']);  // 0
    console.log(arr['input']);  // SESSID=aaaa=;fjsdfjd

What's going on here?

2
  • developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jun 26, 2016 at 16:30
  • 2
    Be aware that adding non-index properties to arrays might make implementations switch the underlying data structure to a hash table (or whatever they use for normal objects). So better don't do it. Commented Jun 26, 2016 at 16:51

1 Answer 1

3

Arrays are just objects. They can have any sort of properties.

The properties whose names are numeric strings are special, because they're bound up in the semantics of the "length" property, but otherwise they're just plain properties too.

I should note that while all of the above is true, there are things to know when adding non-numeric properties to an array. Non-numeric properties do not affect the "length" value, so you can't use .length to see how many there are. More important, non-numeric properties are not included in the output when an array is serialized with JSON.stringify().

Sign up to request clarification or add additional context in comments.

2 Comments

Awesome - thanks! How can I create such an object myself? If I try var test = ['zero', one: 'one'];, I get an Unexpected token : error.
@kcstricks you create the array, and then add properties to it just as you would a plain object. You can't do it with the array initializer syntax however.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.