【发布时间】: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