Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a JavaScript array that has properties?

The RegExp.exec function returns something that looks like a hybrid array. It's an array, but it has properties.

console.log(/d(b+)(d)/i.exec("cdbBdbsbz"));
// => ["dbBd", "bB", "d", index: 1, input: "cdbBdbsbz"]

I can call result[0], result[1], result.index, result.input, etc.

How do I make my own?

[0, 1, "a": 1] is obviously a syntax error, and {"0": 1, "1": 1, "a": 1} does give me an object I can index and access properties of, however it's not the same as what's returned by exec.

I tried doing it with __proto__:

arr = [1, 2, 3];
arr.__proto__.a = 1 // arr.a is 1 now

But console.log doesn't display the property like it does when run on the result of exec, so I suspect it's still not the same thing.

like image 580
crdx Avatar asked Mar 31 '26 15:03

crdx


1 Answers

Easy enough - an array in javascript is just an object, and you can attach any properties you like to it:

var test = ["foo","bar","baz"];
test.index = 1;
test.input="foobarbaz";
console.log(test);

That console.log looks identical to the one returned by regex.exec.

Live example: http://jsfiddle.net/9rCmJ/

like image 144
Jamiec Avatar answered Apr 02 '26 03:04

Jamiec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!