简体   繁体   English

JavaScript中对象数组的访问值

[英]Access value of object array in javascript

I have managed to create an object connecting to an API. 我设法创建了一个连接到API的对象。 So I have a function loadColors() 所以我有一个功能loadColors()

loadColors = function() {

            var Colors = [];
            for (var i =0; i < array.length; i++) {

                Card.get({cardName: array[i].object_name}, function(data) {

                    Colors.push(data.data[0].color);

                });

            }
            return {Colors};
        };
        var Colors = loadColor();

and inside there I was able to see the result with console.log(Colors) which is: 在里面,我可以用console.log(Colors)看到结果:

    Object {Colors: Array[0]}
    Colors: Array[4]
    0: "green"
    1: "red"
    2: "yellow"
    3: "blue"
    length: 4
    __proto__: Array[0]
    __proto__: Object

When I try to access a value like console.log[Colors[0]]; 当我尝试访问类似console.log [Colors [0]];的值时 I get undefined. 我不确定。 What am I doing wring? 我在干什么?

Why are you wrapping Colors in {} in your return statements? 为什么在返回语句Colors {}包装Colors

Just do return Colors; 只需return Colors; and you would be able to access the indexed array items directly from the return result. 并且您将能够直接从返回结果访问索引数组项。

Since you're currently returning an object containing the array, you would have to access it by Colors.Colors[0] . 由于当前正在返回包含数组的对象,因此必须通过Colors.Colors[0]对其进行访问。


Update 更新

I realize that besides wrapping your result in an object before returning it, you are also returning an array that is not populated with items at the return point, due to the asynchronous nature of Card.get . 我意识到,除了返回结果之前将结果包装在对象中,由于Card.get的异步特性,您还将返回一个未在返回点填充项目的Card.get

This problem is actually rather well suited for a concept called Promises , but rather than introducing another new concept at this point, I will illustrate how you can solve this manually. 这个问题实际上非常适合于一个称为Promises的概念,但是在这一点上,除了介绍另一个新概念之外,我将说明如何手动解决这个问题。 (IE doensn't have native Promise support, there are frameworks that will solve this but you may not want an entire new framework just for this. jQuery has something called Deferreds, but they're subtly different from the Promise specs). (IE没有本地Promise支持,有一些框架可以解决此问题,但您可能不希望为此而使用一个全新的框架。jQuery有一个称为Deferreds的东西,但它们与Promise规范有细微差别 )。

Instead of returning a result from the function, the callback from Card.get should call the function that moves your code forward. Card.get回调而不是从函数返回结果,应调用使代码向前移动的函数。 It should only do this once the array is filled, however, and not once for every callback. 但是,仅应在填充数组后执行此操作,而不应为每个回调执行一次。

Card.get({ your options }, function(data) {
    Colors.push(data.data[0].color);
    if(Colors.length == array.length) {
        allColorsLoaded(Colors);
    }
});

So if your logic is currently: 因此,如果您的逻辑当前为:

var Colors = loadColors();
alert(Colors.length);

It would need to be updated so that everything that relies on Colors to be populated is initiated by the callback: 它需要进行更新,以便所有依赖于要填充的Colors东西都由回调启动:

var allColorsLoaded = function(Colors) {
   alert(Colors.length);
};
loadColors();

It is isn't so clear from the question what is going on but from what I understood, when you try 从发生的问题还不清楚,但是从我的理解开始,当您尝试

console.log(Colors[0])

outside the function it returns undefined while inside the function it returns 'green'? 在函数外部返回未定义,而在函数内部返回“绿色”?

If so you should probably just change: 如果是这样,您可能应该更改:

return {Colors};

to be: 成为:

return Colors;

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

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