Javascript: 一次在多个数组上使用 foreach

Javascript: using foreach on multiple arrays at once

我有 2 个 arrays 或更有可能 NodeLists,

const mainSlides = document.querySelectorAll('.mainSlides')
const thumbSlides = document.querySelectorAll('.thumbSlides')

目前我正在像这样迭代它们:


mainSlides.forEach(slide => {
    slide.style.backgroundColor = `red`
})

thumbSlides.forEach(slide => {
    slide.style.backgroundColor = `red`
})

因为他们都设置相同 属性 即; background-color:red;,是否有 shorthand 方式同时遍历两个节点列表?

const mainSlides = document.querySelectorAll('.mainSlides')
const thumbSlides = document.querySelectorAll('.thumbSlides')

mainSlides.forEach(slide => {
    slide.style.backgroundColor = `red`
})

thumbSlides.forEach(slide => {
  //  slide.style.backgroundColor = `red`
})
<div class="holder">
  <div class="mainSlides"> some mainSlides </div>
  <div class="mainSlides"> some mainSlides </div>
  <div class="mainSlides"> some mainSlides </div>
  <div class="mainSlides"> some mainSlides </div>
</div>

 <div class="holder">  
  <div class="thumbSlides"> some mainSlides </div>
  <div class="thumbSlides"> some mainSlides </div>
  <div class="thumbSlides"> some mainSlides </div>
  <div class="thumbSlides"> some mainSlides </div>
</div>

是的,您可以 select 两者合而为一 select 或者:

const mainAndThumbSlides = document.querySelectorAll('.mainSlides,.thumbSlides')

您可以 select 同时 mainSlidesthumbSlides 像这样:

const allSlides = document.querySelectorAll('.mainSlides, .thumbSlides');

或者,如果您不想将它们 select 一起使用(例如,如果您想进一步单独使用它们),而只想将它们一起用于此特定操作:

const allSlides = [...mainSlides, ...thumbSlides];
allSlides.forEach(slide => {
    slide.style.backgroundColor = 'red';
})