微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

访问 forEach 循环内的变量

如何解决访问 forEach 循环内的变量

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

解决方法

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

,

问题

  • bestPrice 每次循环都会被覆盖。
  • instrumentsContainer.innerHTML 每次循环都会被覆盖。
  • 您无需访问 injectInstruments 即可插入 html,因为 .innerHTML = '' 会更改 html。
  • injectInstruments =instrumentsContainer.innerHTML='<div ...>' 有 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);
<div></div>


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

const allInstruments = [{
    price: 100,];

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

console.log(bestPrice)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。