I have managed to create an object connecting to an API. So I have a function 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:
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]]; I get undefined. What am I doing wring?
Why are you wrapping Colors
in {}
in your return statements?
Just do 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]
.
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
.
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. (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).
Instead of returning a result from the function, the callback from Card.get
should call the function that moves your code forward. 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:
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.