简体   繁体   English

如何在JavaScript中迭代数组对象?

[英]How can I iterate an array object in javascript?

I have been on this problem for some hours. 我已经在这个问题上待了几个小时了。 The code work like these : someone does an image search, I fetch the answer from an API and I inject the images into a div to present the result. 代码的工作方式如下:有人进行图像搜索,我从API中获取答案,然后将图像注入div以呈现结果。 It can vary from 3 to 500 images, it's not fixed. 它可以从3到500张图像变化,但不固定。

Except that I cannot manage to display only the right number of images. 除非我无法显示正确数量的图像。 The problem is in the iteration or the way I present data, but after trying everything and anything I think I need help. 问题出在迭代或我呈现数据的方式上,但是尝试了一切之后,我认为我需要帮助。

What I receive from the API comes in this form: 我从API收到的内容是这种形式的:

{"icon":{"0":"https://address/1587.svg","1":"https://address/3810.svg","2":"https://address/89090.svg","3":"https://address/89400.svg"}}

And here's my (simplified) code: 这是我的(简化)代码:

makeHTTPRequest('GET', url).then((resp) => {
        var parsedResp = JSON.parse(resp);
        var arrayicon = Object.keys(parsedResp).map(function(key) {
            return parsedResp[key]
        });
        injectIcons(arrayicon)
        }; 

        injectIcons = (icons) => {
        let htmlString = '';

        for (var i = 0; i < icons.length; i++) {
            const IconDiv = `src="${icons[i]}"`;
            htmlString = htmlString + IconDiv
        }

        document.getElementById('results').innerHTML = htmlString
    };

Try to change the code like this: 尝试像这样更改代码:

var response = {"icon":{"0":"https://address/1587.svg","1":"https://address/3810.svg","2":"https://address/89090.svg","3":"https://address/89400.svg"}}

var icons = response.icon;

for (var k in icons ) {
     const IconDiv = `src="${icons[k]}"`;
     htmlString = htmlString + IconDiv
}

In this case, a simple while loop could work (assuming you can't change the API to return an actual Array --which would be better): 在这种情况下,可以使用一个简单的while循环(假设您无法更改API以返回实际的Array会更好):

 const data = {"icon":{"0":"https://address/1587.svg","1":"https://address/3810.svg","2":"https://address/89090.svg","3":"https://address/89400.svg"}}; let i = 0; while (data.icon[i]) { console.log(data.icon[i++]); } 

Edit: Your code is actually really close to working. 编辑:您的代码实际上真的接近工作。 You just need to access parsedResp.icon rather than parsedResp : 您只需要访问parsedResp.icon而不是parsedResp

 var parsedResp = {"icon":{"0":"https://address/1587.svg","1":"https://address/3810.svg","2":"https://address/89090.svg","3":"https://address/89400.svg"}}; var arrayicon = Object.keys(parsedResp.icon).map(function(key) { return parsedResp.icon[key] }); console.log(arrayicon); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM