Home > Software design >  How can I properly loop with arrays?
How can I properly loop with arrays?

Time:09-23

I am learning arrays through here: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Arrays#active_learning_printing_those_products!

I've given my take for their assignment and I can't tell what I'm doing wrong, despite using their Show Solution option.

const list = document.querySelector('.output ul');
const totalBox = document.querySelector('.output p');
let total = 0;
list.innerHTML = '';
totalBox.textContent = '';
// number 1
let products = ['Underpants:6.99',
                'Socks:5.99',
                'T-shirt:14.99',
                'Trousers:31.99',
                'Shoes:23.99'];
                
// number 2
for (let i = 0; i < products.length; i  ) {
// number 3
  let prices = products[i].split(':');
  let stringPrices = Number(prices);


  for (let z = 0; z < stringPrices.length; z  ) {
// number 4
    let total[z]  = stringPrices
  }

// number 5
  let itemText = `${products[i] — ${prices[i]}` ;

  const listItem = document.createElement('li');
  listItem.textContent = itemText;
  list.appendChild(listItem);
}

totalBox.textContent = 'Total: $'   total.toFixed(2);

The output should eventually be:

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

Would very much appreciate your feedback. Thank you kindly

CodePudding user response:

const list = document.querySelector('.output ul');
const totalBox = document.querySelector('.output p');
let total = 0;
list.innerHTML = '';
totalBox.textContent = '';
// number 1
let products = ['Underpants:6.99',
                'Socks:5.99',
                'T-shirt:14.99',
                'Trousers:31.99',
                'Shoes:23.99'];
          
for (let i = 0; i < products.length; i  ) {
  let prices = products[i].split(':');
  let itemText = `${products[i]} - ${prices[1]}`;
  total  = parseFloat(prices[1])
  const listItem = document.createElement('li');
  listItem.textContent = itemText;
  list.appendChild(listItem);
}

totalBox.textContent = 'Total: $'   total.toFixed(2);

Try this one

  • Related