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 ?
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
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With