1

I am trying to loop through a nested array but not able to display. I am new to Javascript any help would be appreciated. Thank you

let shoppingList = [
  ['Shirts', 'Pants', 'Tie', 'Belt'], 
  ['Fruits', 'Vegetables', 'Spices', 'Utensils'],
  ['Toilet paper', 'Washing liquid', 'Brushes', 'Sponges']
];

//accessing the above array using for loop
for(let shoppingIndex=0; shoppingIndex < shoppingList.length; shoppingIndex++) {
  document.querySelector('p').innerHTML = shoppingList(shoppingIndex);
}
<p> </p>

5
  • You should be using square brackets ([ ]) to read an item from an array, i.e shoppingList[shoppingIndex] Commented Nov 19, 2017 at 17:12
  • Shoppinglist is not a function. You dont want to call it () you want to access it [] => shoppingList[shoppingIndex] Commented Nov 19, 2017 at 17:12
  • String literals delimited with quotes cannot span more than one line. Commented Nov 19, 2017 at 17:13
  • Thank you did'nt see that mistake!!! idiot I am :D. Works now properly. Commented Nov 19, 2017 at 17:13
  • I am not able to retrieve all the array's elements. Any solution for that please? Commented Nov 19, 2017 at 17:16

2 Answers 2

1

You need to access the list items using []. Also at the moment you will only ever display the last array, to display all arrays you can use += and instead of using innerHTML you can use textContent since you're simply displaying text with no HTML.

let shoppingList = [
  ['Shirts', 'Pants', 'Tie', 'Belt'], 
  ['Fruits', 'Vegetables', 'Spices', 'Utensils'], 
  ['Toilet paper', 'Washing liquid', 'Brushes', 'Sponges']
];

//accessing the above array using for loop
for(let shoppingIndex=0; shoppingIndex<shoppingList.length; shoppingIndex++) {
   document.querySelector('p').textContent += shoppingList[shoppingIndex];
}
<p></p>

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

2 Comments

Thank you!! can you please explain me what does += do?
No problem, it means to append text to the existing text instead of overwriting it.
0

let shoppingList = [['Shirts', 'Pants', 'Tie', 'Belt'], 
['Fruits', 'Vegetables', 'Spices', 'Utensils'], ['Toilet paper', 
'Washing liquid', 'Brushes', 'Sponges']];

//accessing the above array using for loop
for(let shoppingIndex=0; shoppingIndex<shoppingList.length; 
shoppingIndex++) {
 document.querySelector('p').innerHTML +=  shoppingList[shoppingIndex] + '<br>';
}
<p> </p>

You are accessing property using () access with [], and if you want to print with next line concatenate using <br>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.