Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Array construction with spread syntax and map doesn't work #546

Closed
codeKonami opened this issue Jun 12, 2018 · 5 comments
Closed

Array construction with spread syntax and map doesn't work #546

codeKonami opened this issue Jun 12, 2018 · 5 comments

Comments

@codeKonami
Copy link

I use this syntax quite a lot to create my Arrays

const foos =
    [...Array(4)]
        .map(x => 'foo');
// ['foo', 'foo', 'foo', 'foo']

But on your platform the array has the good size but of "undefined" element.

See here : https://stackblitz.com/edit/js-mtffex

@tiliev tiliev added question and removed question labels Jun 12, 2018
@seveves
Copy link
Collaborator

seveves commented Jun 21, 2018

Your pattern should definitely work but how about using Array.from({ length: 4 }, x => 'foo')); 😎

@codeKonami
Copy link
Author

@seveves That's a really nice way to do it too :)
Thanks

@gdlm91
Copy link

gdlm91 commented Nov 13, 2019

I'm having the same problem while trying to create a range of numbers using this pattern:

const minNumber = 1;
const maxNumber = 10;

const rangeArr = [...Array(maxNumber - minNumber + 1)].map(
  (item, index) => index + minNumber
);

console.log(rangeArr);

returns

[undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined]

Instead of

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Tried the same pattern in other platforms and they work correctly:

Using @seveves pattern works correctly:

const minNumber = 1;
const maxNumber = 10;

const rangeArr = Array.from(
  { length: maxNumber - minNumber + 1 }, 
  (item, index) => index + minNumber
);

console.log(rangeArr);

@jayphelps
Copy link

jayphelps commented Feb 3, 2020

A seemingly related issue is how spreading works in general. It seems that however Stackblitz is doing compilation, it's in some sort of very loose mode that IMO is way too lose for something like Stackblitz.

e.g. [...something] is always compiled to something.slice() which is a big no-no because something can be anything iterable, including a Set which doesn't have slice, concat, etc.

My guess is its maybe its using an old version of babel's loose mode--the latest versions of loose mode don't seem to do this but it might have in the past.

@sulco
Copy link
Member

sulco commented Jan 25, 2021

Good catch everyone, thanks for reporting this!
Yeah, it was confusing...

Thankfully it should no longer be an issue :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants