繁体   English   中英

尝试遍历两个 arrays 并在 JavaScript 中正确格式化它们的 output

[英]Trying to loop through two arrays and format their output properly in JavaScript

我是 javascript 的新手,我正在学习通过 arrays 循环。 无论如何,我有一组价格和一组名称。 我希望 output 为:“名称:价格”。 例如:磅:454 半磅:227 四分之一磅:114 等....

然而,由于某种原因,我得到的 output 是每个名称的重复,每个名称旁边都有每个价格,如下面的片段所示。 我在这里先向您的帮助表示感谢。 :)

 const salePrices = [454,227,114,28,14,7,3.5]; const names = ['Pound','Half-Pound','Quarter Pound','Ounce','Half Ounce','Quarter Ounce','Eighth']; for (let i = 0; i < salePrices.length; i++){ for(let x = 0; x < names.length; i++){ console.log(`${names[x]}:${salePrices[i]}`) } }

你不需要两个循环。 一个循环就足以获取index ,然后从中获取namessalePrices ,如下所示:

 const salePrices = [454, 227, 114, 28, 14, 7, 3.5]; const names = [ "Pound", "Half-Pound", "Quarter Pound", "Ounce", "Half Ounce", "Quarter Ounce", "Eighth", ]; for (let i = 0; i < salePrices.length; i++) { console.log(`${names[i]}: ${salePrices[i]}`); }

是的,这是因为每次外循环迭代一次,内循环就完全运行。 因此,对于每个销售价格名称都已满。

如果两个 arrays 的顺序已经正确,您可以只使用一个for循环。

 const salePrices = [454, 227, 114, 28, 14, 7, 3.5]; const names = [ "Pound", "Half-Pound", "Quarter Pound", "Ounce", "Half Ounce", "Quarter Ounce", "Eighth", ]; for (var i = 0; i < salePrices.length; i++) { console.log(names[i] + ":" + salePrices[i]) }

我假设您的意思是在 for 循环中增加x而不是i

在第一个 for 循环中,您正在遍历salePrices 因此salePrices[i]会给你454 -> 227 -> 114 -> 28 -> 14 -> 7 -> 3.5
在第二个 for 循环中,您正在遍历names 因此names[x]将为您'Pound' -> 'Half-Pound' -> 'Quarter Pound' -> 'Ounce' -> 'Half Ounce' -> 'Quarter Ounce' -> 'Eighth'

但是,第二个 for 循环嵌套在第一个 for 循环内。 因此,所有names都针对每个销售价格进行了迭代。 前任:
i=0时,它将打印:

Pound:454
Half-Pound:454
Quarter Pound:454
etc...

如果您确定namessalePrices的长度相同。 您可以使用decpk 的答案

您也可以将它们设为 object,而不是将names作为键, salePrices作为值(这可能更适合此用例)。

 const products = { "Pound": 454, "Half-Pound": 227, "Quarter Pound": 114, "Ounce": 28, "Half Ounce": 14, "Quarter Ounce": 7, "Eighth": 3.5, }; for (const [name, price] of Object.entries(products)) { console.log(`${name}: ${price}`); }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM