2

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.

4 Answers 4

5

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/

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

Comments

3

Do you mean this?

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

Comments

3

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

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

Comments

3

Do it in two steps:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.