Hi i am having a problem in java script with function and arrays

Viewed 43

Print a shopping list Create a function called print Shopping List that take a list of products and print the items to the screen.

//
 shopping List = [
    { item Name : 'Bread', price : 11.00 },
    { item Name : 'Milk', price : 7.00 },
    { item Name : 'Cheese', price : 19.50 }
];
This should print:

Shopping list:
* Bread @ R11.00
* Milk @ R7.00
* Cheese @ R19.50
4 Answers
console.log('Shopping List:');
shoppingList.forEach(ele => {
console.log('*'+ele.ItemName+'@'+'R'+ele.price);
);

Hope this helps.

You can try the below code. Hope it helps.

const shoppingList = [{
    itemName: 'Bread',
    price: 11.00
  },
  {
    itemName: 'Milk',
    price: 7.00
  },
  {
    itemName: 'Cheese',
    price: 19.50
  }
];

const itemsHTML = shoppingList.map(item => (
  `<li>${item.itemName} @ R${item.price}</li>`
))

document.write(`<ul>${itemsHTML}</ul>`);

You can simply achieve it by creating a node in the HTML DOM and create the custom string by using template string.

Demo :

const shoppingList = [
    { itemName : 'Bread', price : 11.00 },
    { itemName : 'Milk', price : 7.00 },
    { itemName : 'Cheese', price : 19.50 }
];

shoppingList.forEach(item => {
  const node = document.createElement("li");
  const liNode = document.getElementById('priceList').appendChild(node);
  liNode.innerHTML = `${item.itemName} @ R${item.price}`
});
<ul id="priceList"></ul>

Your syntax is wrong in a lot of ways. An identifier (variable name, function name, etc. — “identifier” is programming jargon for “name”) cannot contain a space in almost all programming/scripting languages. So, shopping list should be shoppingList (or shopping_list), item name should be itemName or, even better, just name. As you see in the forEach part, naming the running position item, I access the name using item.name.

const shoppingList = [
  { name: 'Bread',  price: 11.00 },
  { name: 'Milk',   price:  7.00 },
  { name: 'Cheese', price: 19.40 },
];

shoppingList.forEach(item => {
  console.log(item.name + " @ R" + item.price.toFixed(2));
})
Related