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 ?

2
  • 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) Commented Oct 26, 2020 at 13:53
  • 1
    new Array(5); - this will create a sparse array with only length property and no array elements. Commented Oct 26, 2020 at 13:56

1 Answer 1

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]);
  });

Sign up to request clarification or add additional context in comments.

5 Comments

beside " for (field in arrayobj)" , Can I use for (var i=0; i<arrayobj.length; i++) to loop on the arrayobj? Because stackoverflow.com/questions/1345939/…. mention some way to get the size of the object
You can use Object.keys(arrayObj).length to get the length however using arrayObj.length directly will return undefined
therefore , for (var i=0; i<Object.keys(arrayObj).length ;i++) can loop on the arrayobj ?
@SamLi yes, kindly check the updated snippet on how to loop over an object
@SamLi also kindly accept the answer it if addresses your issue, thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.