【问题标题】:Trying to loop through two arrays and format their output properly in JavaScript尝试遍历两个数组并在 JavaScript 中正确格式化它们的输出
【发布时间】:2022-01-22 15:07:54
【问题描述】:

我是 javascript 新手,我正在学习循环数组。无论如何,我有一组价格和一组名称。我希望输出为:“名称:价格”。例如: 英镑:454 半磅:227 四分之一磅:114 等等……

但是由于某种原因,我得到的输出是每个名称的重复,每个名称旁边都有每个价格,正如您在下面的 sn-p 中看到的那样。我在这里先向您的帮助表示感谢。 :)

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]}`)
  }
}

【问题讨论】:

  • 您正在创建一个无限循环,因为您没有在内部循环中增加x 的值。你不需要两个循环。

标签: javascript arrays


【解决方案1】:

你不需要两个循环。一个循环就足以获取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]}`);
}

【讨论】:

  • 感谢您提供此解决方案。有道理。
【解决方案2】:

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

如果两个数组的顺序已经正确,您可以只使用一个 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])
}

【讨论】:

    【解决方案3】:

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

    在第一个 for 循环中,您正在遍历 salePrices。因此salePrices[i] 会得到你454 -&gt; 227 -&gt; 114 -&gt; 28 -&gt; 14 -&gt; 7 -&gt; 3.5
    在第二个 for 循环中,您正在遍历 names。因此names[x] 会得到你'Pound' -&gt; 'Half-Pound' -&gt; 'Quarter Pound' -&gt; 'Ounce' -&gt; 'Half Ounce' -&gt; 'Quarter Ounce' -&gt; 'Eighth'

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

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

    如果您确定namessalePrices 的长度相同。你可以使用decpk's answer

    您也可以将它们设为对象,以 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}`);
    }

    【讨论】:

      猜你喜欢
      • 2019-11-17
      • 2014-03-06
      • 1970-01-01
      • 2016-03-22
      • 1970-01-01
      • 2022-08-22
      • 2019-02-02
      • 2014-05-11
      • 1970-01-01
      相关资源
      最近更新 更多