Luca Bertoldi
Luca Bertoldi

Reputation: 11

Why does this for loop only print one element?

Could you help me with this problem I found on MDN?

var list = document.querySelector('.output ul');
var totalBox = document.querySelector('.output p');
var total = 0;

list.innerHTML = '';
totalBox.textContent = '';

var products = [
  'Underpants:6.99',
  'Socks:5.99',
  'T-shirt:14.99',
  'Trousers:31.99',
  'Shoes:23.99'
];

for (var i = 0; i < products.length; i++) {
  var subArray = products[i].split(':');
  var name = subArray[0];
  var price = Number(subArray[1]);

  total += price;
  itemText = name + ' — $' + price;

  var listItem = document.createElement('li');

  listItem.textContent = itemText;
  list.appendChild(listItem);
}

totalBox.textContent = 'Total: $' + total.toFixed(2);
<div class="output">
  <ul></ul>
  <p></p>
</div>

I understand the logic but when I write only this part of the code below on my console, it returns only "Socks:5.99":

var products = [
  'Underpants:6.99',
  'Socks:5.99',
  'T-shirt:14.99',
  'Trousers:31.99',
  'Shoes:23.99'
];

for (var i = 0; i < products.length; i++) {
  var subArray = products[i].split(':');
  var name = subArray[0];
  var price = Number(subArray[1]);
}

And the subArray contains only that element. It seems like the for loop doesn’t work. Shouldn’t it give me an entire new Array with:

Underpants — $6.99
Socks — $5.99
T-shirt — $14.99
Trousers — $31.99
Shoes — $23.99

Upvotes: 0

Views: 581

Answers (1)

giuseppedeponte
giuseppedeponte

Reputation: 2381

Your code works, you just have to store each iteration result somewhere, like in a new array. Here is an example:

var products = [
  'Underpants:6.99',
  'Socks:5.99',
  'T-shirt:14.99',
  'Trousers:31.99',
  'Shoes:23.99'
];

var formattedProducts = [];

for (var i = 0; i < products.length; i++) {
  var subArray = products[i].split(':');
  var name = subArray[0];
  var price = Number(subArray[1]);
  formattedProducts.push(name + ' - $' + price);
}

console.log(formattedProducts);

Edit

In your first code example, the result was stored directly in your DOM, inside the .output ul list element:

  var listItem = document.createElement('li');

  listItem.textContent = itemText;
  // list is defined outside the loop and will receive a new li element with the result of the iteration as textContent
  list.appendChild(listItem);

Upvotes: 3

Related Questions