Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does result of `String.match` array contains index, group, etc.,?

I just got wondered how come the result of regexp match in Javascript returns an one-dimensional array with keyed indexes ?

var str = "We will";

const result = str.match(/wi/);

console.log(Array.isArray(result));
console.log(result.index);
console.log(result.input);

Here how does the array is having string based keys("index", "input", etc.,). Is there way we can create an array like this in Javascript ?

like image 633
Kamalakannan J Avatar asked Nov 01 '25 21:11

Kamalakannan J


1 Answers

Yes, there is. Arrays are just iterable objects in JavaScript. MDN states:

Arrays are list-like objects whose prototype has methods to perform traversal and mutation operations.

This means you can simply assign a property. Be careful though to not accidentally overwrite an existing property while doing so:

const arr = [1, 2, 3];

arr.propName = 42;

console.log(
  ...arr,
  arr.propName
);
like image 118
JJWesterkamp Avatar answered Nov 04 '25 11:11

JJWesterkamp