crdx
crdx

Reputation: 1432

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.

Upvotes: 2

Views: 165

Answers (4)

sphair
sphair

Reputation: 1670

Do it in two steps:

var a = [1, 2, 3];
a.test = "Hello world";

Upvotes: 3

Jamiec
Jamiec

Reputation: 136154

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/

Upvotes: 5

luin
luin

Reputation: 1995

An array is also an object, so you can set property directly:

var myArray = ['a', 'b'];
console.log(typeof myArray); // 'object'
myArray.say = 'hi';

Upvotes: 3

Álvaro González
Álvaro González

Reputation: 146568

Do you mean this?

var arr = [0, 1];
arr.a = 1;

Upvotes: 3

Related Questions