gpt4 book ai didi

javascript - 为什么这个 for 循环只打印一个元素?

转载 作者:行者123 更新时间:2023-11-28 16:56:59 25 4
gpt4 key购买 nike

您能帮我解决我在 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>

我理解逻辑,但是当我在控制台上仅编写下面这部分代码时,它仅返回 "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]);
}

并且 subArray 仅包含该元素。看起来 for 循环不起作用。它不应该给我一个全新的数组吗:

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

最佳答案

您的代码可以工作,您只需将每个迭代结果存储在某个地方,例如新数组中。这是一个例子:

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

编辑

在第一个代码示例中,结果直接存储在 DOM 中的 .output ul 列表元素内:

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

关于javascript - 为什么这个 for 循环只打印一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58890146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com