1

I see the example that creates an array using

var array = new Array(5);

but also I see something like this

arrayObj[0] = "index zero";
arrayObj[10] = "index ten";

I think the above code creates an object with two field name 0 and 10 like below? Is that correct?

arrayobj {
0: "index zero"
10: "index ten"
}

any different in this two way to create array using new Array() and new Object ?

SamLi
  • 105
  • 2
  • 11
  • 1
    Just test it: `var arrayObj = []; arrayObj[0] = "index zero"; arrayObj[10] = "index ten"; console.log(arrayObj)` / `var arrayObj = {}; arrayObj[0] = "index zero"; arrayObj[10] = "index ten"; console.log(arrayObj)` – Andreas Oct 26 '20 at 13:53
  • 1
    `new Array(5);` - this will create a sparse array with only `length` property and no array elements. – Yousaf Oct 26 '20 at 13:56

1 Answers1

1

Array and Object are different from eachother. Technically what you are doing makes the data structure and utility for time being as same but you miss on prototype functions and cannot use it crossside.

E.g Array.forEach() will loop on an array but it will not loop on an object whose key/value pair are equivalent to that of index/item of an array

var array = new Array(5).fill('index');

arrayObj = {};
arrayObj[0] = "index zero";
arrayObj[10] = "index ten";
try {
  console.log(array.length);
  array.forEach(i => console.log(i));
  
  

  console.log(arrayObj.length);
  arrayObj.forEach(i => console.log(i));
  } catch (e) { console.error(e); }
  
  //looping over Object
  
  Object.keys(arrayObj).forEach((item)=>{ 
     console.log(arrayObj[item]);
  });
Metabolic
  • 2,808
  • 3
  • 27
  • 41