因此,我尝试通过For循环自动打印大量图像。我有三个列表,分别包含特定类型的图像:森林、人物和海洋。我想要浏览和打印每个类别的每一张照片。我已经尝试了几个小时,但我是一个完全的初学者,所以我可能错过了一些愚蠢的东西。到目前为止,这是我的代码:
<script>
const forrest = ["https://cdn.pixabay.com/photo/2020/03/20/13/23/mountain-4950653_1280.jpg", "https://cdn.pixabay.com/photo/2020/01/07/14/18/forrest-4747692_1280.jpg", "https://cdn.pixabay.com/photo/2018/07/30/11/30/landscape-3572374_1280.jpg"]
const people = ["https://cdn.pixabay.com/photo/2014/09/07/21/52/city-438393_1280.jpg", "https://cdn.pixabay.com/photo/2015/05/15/14/50/concert-768722_1280.jpg", "https://cdn.pixabay.com/photo/2017/08/06/12/06/people-2591874__480.jpg"]
const ocean = ["https://cdn.pixabay.com/photo/2016/11/29/04/19/ocean-1867285_1280.jpg", "https://cdn.pixabay.com/photo/2018/06/13/18/20/wave-3473335__340.jpg", "https://cdn.pixabay.com/photo/2016/12/17/14/33/wave-1913559__340.jpg"]
const type = [forrest, people, ocean]
function myFunction() {
for (var i = 0; i < type.length; i++); {
var list = type[i];
for (var pictures = 0; pictures <= list.length; pictures++); {
var img = document.createElement("img");
img.src = list[pictures];
document.body.appendChild(img);
}
}
}
</script>
我在上面的代码中插入了一些示例照片。我的照片也来自网络。代码打印第一个列表中的第一张照片,但不打印其他任何照片。
发布于 2021-07-14 00:46:54
您在for循环条件后放置了分号:
for (var i = 0; i < some_list.length; i++) /* NO SEMICOLON HERE*/ {
//body
}去掉它们,它就可以工作了:
const forrest = ["https://cdn.pixabay.com/photo/2020/03/20/13/23/mountain-4950653_1280.jpg", "https://cdn.pixabay.com/photo/2020/01/07/14/18/forrest-4747692_1280.jpg", "https://cdn.pixabay.com/photo/2018/07/30/11/30/landscape-3572374_1280.jpg"]
const people = ["https://cdn.pixabay.com/photo/2014/09/07/21/52/city-438393_1280.jpg", "https://cdn.pixabay.com/photo/2015/05/15/14/50/concert-768722_1280.jpg", "https://cdn.pixabay.com/photo/2017/08/06/12/06/people-2591874__480.jpg"]
const ocean = ["https://cdn.pixabay.com/photo/2016/11/29/04/19/ocean-1867285_1280.jpg", "https://cdn.pixabay.com/photo/2018/06/13/18/20/wave-3473335__340.jpg", "https://cdn.pixabay.com/photo/2016/12/17/14/33/wave-1913559__340.jpg"]
const type = [forrest, people, ocean]
function myFunction() {
for (var i = 0; i < type.length; i++) {
var list = type[i];
for (var pictures = 0; pictures < list.length; pictures++) {
var img = document.createElement("img");
img.src = list[pictures];
document.body.appendChild(img);
}
}
}
debugger;
myFunction();
发布于 2021-07-13 22:28:19
您的for循环是错误的。for (var i = 0; i > type.length; i++)意味着只要i大于type.length,for循环就会继续。第一次迭代是:0 > 3,所以它不会工作。您需要检查I是否小于type.length。喜欢:for (var i = 0; i < type.length; i++)
有关更多信息,请查看此处:MDN For LOOP
发布于 2021-07-14 00:45:57
我花了一些时间才找到它,但它是for循环后的分号:
使用
for (var i = 0; i < type.length; i++) {而不是
for (var i = 0; i < type.length; i++); {分号使for循环运行3次,如果在下一行执行console.log(i),您将看到i=3和list[i]未定义
https://stackoverflow.com/questions/68363665
复制相似问题