【问题标题】:Accesing variables inside the forEach loop在 forEach 循环中访问变量
【发布时间】:2021-03-09 05:59:29
【问题描述】:

我在从 forEach 循环中访问变量时几乎没有问题,该循环在循环外围绕对象数组循环。 我已经尝试过声明变量并将它们分配给 forEach 循环中的变量,但它不成功,因为它只返回第一个值。

let bestPrice;
let injectInstruments;
allInstruments.forEach(function (instrument) {
    
    let price = instrument.price;
    let type = instrument.type;
    let description = instrument.description;
    let picture = instrument.picture;
   
     injectInstruments =instrumentsContainer.innerHTML= `<div  hidden 
    instrumentType='${type}'class="box instrument" price="${price}">
        <img class="instrument-image" src="${picture}" alt="">
       <h6 class="price">${price}</h6>
        <p class="instrument-description">${description}</p>
    </div>`
   bestPrice=price
})
console.log(injectInstruments);
console.log(bestPrice);

【问题讨论】:

  • 错误是什么,你想完成什么?提供更多细节。您可以访问 injectInstruments 但它未定义,因此它不会有 innerHtml 属性
  • 所以,我需要在外部访问变量价格、类型等,因为它们将在过滤器中使用,我还需要将这些属性注入到 html 中。问题是,如果我在循环内使用 console.log(injectInstruments),它会给我正确的输出,但在循环外,它是未定义的,并且字符串没有注入 html

标签: javascript arrays foreach


【解决方案1】:

问题

  • bestPrice 在每个循环中都会被覆盖。
  • instrumentsContainer.innerHTML 在每个循环中都会被覆盖。
  • 您无需访问 injectInstruments 即可插入 html,因为 .innerHTML = '' 会更改 html。
  • injectInstruments =instrumentsContainer.innerHTML='&lt;div ...&gt;' 有 3 个等于 =,这会导致语法错误。

解决方案

  • 使用.insertAdjacentHTML() 而不是.innerHTML。前者将html添加到容器中,后者完全覆盖容器的内容。
  • 如果您只想访问价格,请将价格存储在数组中。

// Get the container <div>
const instrumentsContainer = document.querySelector('div');

const allInstruments = [{
    price: 100,
    type: 'something',
    description: 'lorem ipsum',
    picture: './image1.jpg'
  },
  {
    price: 200,
    type: 'something2',
    description: 'lorem ipsum2',
    picture: './image2.jpg'
  },
];

// An array to store prices
let bestPrices = [];
  
function myFunction() {
  allInstruments.forEach(function(instrument) {

    let price = instrument.price;
    let type = instrument.type;
    let description = instrument.description;
    let picture = instrument.picture;

    // HTML
    let html = `<div instrumentType='${type}'class="box instrument" price="${price}">
        <img class="instrument-image" src="${picture}" alt="${picture}">
       <h6 class="price">${price}</h6>
        <p class="instrument-description">${description}</p>
    </div>`;

    // Insert the html to the end of the <div>
    instrumentsContainer.insertAdjacentHTML('beforeend', html);

    // Store a price to the array
    bestPrices.push(price);
  });
}

// Execute myFunction();
myFunction();

// Check bestPrices
console.log(bestPrices);
&lt;div&gt;&lt;/div&gt;

就个人而言,我认为没有必要将价格存储在数组中。如果你想得到最低的价格,你可以这样做:

const allInstruments = [{
    price: 100,
    type: 'something',
    description: 'lorem ipsum',
    picture: './image1.jpg'
  },
  {
    price: 200,
    type: 'something2',
    description: 'lorem ipsum2',
    picture: './image2.jpg'
  },
];

let bestPrice = Math.min(...allInstruments.map(e => e.price));

console.log(bestPrice)

【讨论】:

    【解决方案2】:

    这是因为bestPriceinjectInstrument 的值在每个循环中都会改变。尝试将您的值存储在字符串数组中并通过循环迭代 debug.log。

    【讨论】:

      猜你喜欢
      • 2012-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-26
      • 1970-01-01
      • 2021-06-01
      相关资源
      最近更新 更多