kcstricks kcstricks - 3 months ago 7x
Javascript Question

Javascript array with keys

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?


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