Array.prototype.replace

T.J. Crowder tj.crowder at farsightsoftware.com
Tue Jul 10 06:48:28 UTC 2018


Hi,

The standard library already handles doing array-copy-and-update as a
one-liner via `Object.assign` (http://jsfiddle.net/ryqtvbdk/):

```js
const original = [1, 2, 3, 4];
const updated = Object.assign([...original], {1: 4, 3: 42});
// Or: const updated = Object.assign([], original, {1: 4, 3: 42});
console.log(updated); // [1, 4, 3, 42]
```

Like Isiah, I think I'd prefer it as syntax. I'm not an engine implementer
so I have no idea how hard it would be to do this to an array initializer:

```js
const original = [1, 2, 3];
const updated = [...original, 1: 4];
console.log(updated); // [1, 4, 3]
```

...but that's what I'd like to see. Parallels the object initializer.
Currently invalid syntax, so safe to add from that perspective. And it
enhances destructuring as well (since array initializer syntax is used for
destructuring):

```js
const original = [1, 2, 3];
const [1: foo, ...rest] = original;
console.log(foo); // 2
console.log(rest); // [1, 3]
```

(Note that `rest` is an array, whereas with an object destructuring
pattern, it would be a non-array object.)

That syntax would also provide expressive creation of sparse arrays, e.g.:

```js
const array = [2: 42];
console.log(array); // [, , 42];
```

-- T.J. Crowder
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20180710/ac8b2ecf/attachment.html>


More information about the es-discuss mailing list