In Javascript: Losing type of object when passed from Array?
I'm passing an object of a certain type to an array. When I pr开发者_如何学Pythonint 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 in
loop, 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 the 0 = 0
, because the first index of your array (you have one element) is 0
.
Use this instead:
printObjectProperties(array[obj]);
which would evaluate to:
printObjectProperties(array[0]);
or:
printObjectProperties(test);
You don't iterate over an array using for in:
for (var i = 0, len = array.length; i < len; ++i) {
console.log(array[i]);
}
精彩评论