I’m passing an object of a certain type to an array.
When I print the object from an outside reference I can see all the fields.
When I print the same object from the array reference, I see almost none.
To Explain, here is the code that illustrates the problem:
var test = new OpenLayers.Layer.Vector();
var array = [test];
console.log("******* Printing Test directly ***************");
printObjectProperties(test);
console.log("****** Printing Test from array **************");
for (obj in array){
printObjectProperties(obj);
}
The printObjectProperties() function:
function printObjectProperties(eventData) {
for (var prop in eventData) {
if (!(typeof (eventData[prop]) == "undefined")) {
console.log(prop + " = " + eventData[prop]);
}
};
}
The complete code (complete html file, you can run and see for youself in the browser console log):
(live example)
<html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script src="http://www.openlayers.org/api/OpenLayers.js"></script>
<script>
$(document).ready(function(){
var test = new OpenLayers.Layer.Vector();
var array = [test];
console.log("******* Printing Test directly ***************");
printObjectProperties(test);
console.log("****** Printing Test from array **************");
for (obj in array){
printObjectProperties(obj);
}
});
function printObjectProperties(eventData) {
for (var prop in eventData) {
if (!(typeof (eventData[prop]) == "undefined")) {
console.log(prop + " = " + eventData[prop]);
}
};
}
</script>
</html>
In a
for inloop, the first variable (obj) is the key. In an array that’s the index.So basically you’re iterating over a number in
printObjectProperties. Hence the0 = 0, because the first index of your array (you have one element) is0.Use this instead:
which would evaluate to:
or: