for循环里面的for循环用于生成字符串

For loop inside for loop for generating strings

我有以下代码根据 objects 及其属性的数组生成图像 url:

for (let s = 0; s < amount; s++) {
   console.log(projects[s].imagelocation + projects[s].images[0]); 
}  

作为一个例子,这给了我以下输出:

img/EnergyGoStix-assets/GoStix1.jpg
img/Premier-assets/PremierStudios1.jpg
img/Quickstix-assets/QuickStix1.jpg
img/MotherMonster-assets/MotherMonster1.jpg
img/Stepping-assets/SteppingBooklet1.jpg

但是,images属性实际上是一个数组。此数组包含多个图像源,例如 GoStix1.jpgGoStix2.jpg 等。图像源的数量因项目而异。

如何在一个循环中创建一个循环,其中包含 images.length 它首先会遍历每个项目并生成所有图像源,然后再进入下一个项目?

P.S - 抱歉 post 标题太糟糕了,不知道该称呼什么。如果有人能想出更好的方法来帮助更精确,请告诉我,以便我更新。

只是嵌套循环,注意在每个循环的初始化中使用不同的变量名。

for (let s = 0; s < amount; s++) {
  for (let i = 0; i < projects[s].images.length; i++) {
    console.log(projects[s].imagelocation + projects[s].images[i]);
  }
}

比另一个 for 循环更好的方法是使用数组迭代方法:

for (let s = 0; s < amount; s++) {
  projects[s].images.forEach(image => {
      console.log(projects[s].imagelocation + image);
  });
}

这个怎么样?

for (let s = 0; s < amount; s++) {
for (let y in  projects[s].images){
   console.log(projects[s].imagelocation + projects[s].images[y]); 
}
} 

如果只想在一个控制台中显示图像数组,请使用:

for (let s = 0; s < amount; s++) {
   console.log(projects[s].imagelocation + [...projects[s].images]); 
}