Array.prototype.replace
Ben Wiley
therealbenwiley at gmail.com
Tue Jul 10 12:22:15 UTC 2018
T.J., thanks for pointing out that Object.assign provides the same
functionality. I'd neglected to consider that the first argument needn't be
a plain object.
Interesting that folks seems to prefer the syntax variant more than I had
expected.
As for the application of providing a destructuring parallel.. well, you've
convinced me it could be useful. :)
Here's a spec question: must the keys specified be numbers? The application
is questionable but I say anything could be allowed. E.g.
```js
const arr1 = [1,2,3]
const arr2 = [...arr1, foo: 'bar' ]
```
Or
```js
const [ 1: middle, foo, ...arr3 ] = arr2
console.log(middle, foo, arr3) // 2 "bar" [1, 3]
```
So array rest spread would provide totally parallel functionality to object
rest spread with the key difference that result objects are arrays instead
of objects.
Thoughts?
Ben
Le 10 juill. 2018 02 h 48, "T.J. Crowder" <tj.crowder at farsightsoftware.com>
a écrit :
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/32662696/attachment.html>
More information about the es-discuss
mailing list