0

I wanna create a function(m ,n){}, return a array, it's length of m, each value is n

function createArray(m, n){
  let a = new Array(6);
  return a.map(item => n)
}
const z = createArray(5,6);
console.log(z)

I supposed z will be a array of 6 why z is a array of undefined?

Liuuil
  • 1,441
  • 3
  • 16
  • 22
  • You are creating an array of length 6 with undefined values. `new Array(6)` does that. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Syntax – Saugat Aug 05 '17 at 16:50
  • This has been answered quite a few times already. – rossipedia Aug 05 '17 at 16:50
  • 1
    `return [...a].map(item => n)` – A.Akram Aug 05 '17 at 16:51
  • @A.Akram it works, can u instruct why my style is not working a little bit? – Liuuil Aug 06 '17 at 02:19
  • @Liuuil, I'm not expert, but as I understand: `new Array(6)` has the same effect as `a=[]; a.length=6`. Which only sets the length without allocating real slots. it seems `map` iterate through "defined" slots not as you expect to iterate through 0 => array's length . – A.Akram Aug 08 '17 at 11:40

1 Answers1

0

z is indeed an array of 6, but 6 empty slot because your new Array does just create an empty array with 6 slots but no value

Pre ES6

let arr = new Array(10).fill('5');

You can check the link on top, speaking about this case (JavaScript "new Array(n)" and "Array.prototype.map" weirdness)

sheplu
  • 2,937
  • 3
  • 24
  • 21