gpt4 book ai didi

javascript - 如何在 JavaScript 的数组中存储值?

转载 作者:行者123 更新时间:2023-11-28 14:38:33 24 4
gpt4 key购买 nike

我的 JavaScript 代码是:

<script type="text/javascript">
var photo = {"cover1":"arsenal.jpg", "cover2":"liverpool.jpg"};
var photoList = [
{"id":1, "name":"chelsea.jpg"},
{"id":2, "name":"mu.jpg"},
{"id":3, "name":"arsenal.jpg"},
{"id":4, "name":"city.jpg"},
{"id":5, "name":"liverpool.jpg"}
];
for (var i = 0; i < photoList.length; i++) {
if(photoList[i].name == photo.cover1 || photoList[i].name == photo.cover2) {
console.log(photoList[i].id)
}
}
// I want to store it in array like this = [3,5]
</script>

console.log(photoList[i].id)的结果是3和5。

我想将它存储在一个数组中,如下所示:[3,5]。因此,如果满足 if 条件,则该值将存储在数组中

我该怎么做?

最佳答案

您可以创建一个数组并将其插入其中。就像

<script type="text/javascript">
var photo = {"cover1":"arsenal.jpg", "cover2":"liverpool.jpg"};
var photoList = [
{"id":1, "name":"chelsea.jpg"},
{"id":2, "name":"mu.jpg"},
{"id":3, "name":"arsenal.jpg"},
{"id":4, "name":"city.jpg"},
{"id":5, "name":"liverpool.jpg"}
];
var result = []
for (var i = 0; i < photoList.length; i++) {
if(photoList[i].name == photo.cover1 || photoList[i].name == photo.cover2) {
result.push(photoList[i].id);
}
}
// I want to store it in array like this = [3,5]
</script>

关于javascript - 如何在 JavaScript 的数组中存储值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49050794/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com