$.each() not properly iterating over array
I am having an issue iterating over an associative array with jQuery. I have four spans in the html page... and I use json to form an array of the text() values from those to build an array of dimensions
var export_pkg = {
height : $('#cubeiq_hght').text(),
length : $('#cubeiq_lnth').text(),
depth : $('#cubeiq_wdth').text(),
weight : $('#cubeiq_wght').text()
};
$.each(export_pkg, function(key,value){
alert(key + ' ' + value);
});
For a reason I cannot figure out..开发者_运维知识库. the length of export_pkg is always the text value for length within the array. Both Firefox and IE's developer tools shows export_pkg to be an array with 4 items and it has the correct value. But when I get to the $.each block... it ignores the object and just uses the second entry as the length of the object.
Example: If the array had a {length: 10} the alert box appears 10 times no matter what the value of the others is. I cannot figure out for the life of me why it does not run 4 times as I would expect it to.
Here is a jslint link http://jsfiddle.net/fFDfU/
First, you isn't using an array, it's an object. But you can iterate object properties using each
as you want.
The length
property is used by each
to see how many items need to be iterated. Since you have a length
inside your object, it confuses each
.
I suggest you to change that property name: http://jsfiddle.net/ErickPetru/fFDfU/1/
What you have is not an array of objects but an object with properties. An array is defined like this:
var array = [
{
height : $('#cubeiq_hght').text(),
length : $('#cubeiq_lnth').text(),
depth : $('#cubeiq_wdth').text(),
weight : $('#cubeiq_wght').text()
},
{
height : $('#cubeiq_hght').text(),
length : $('#cubeiq_lnth').text(),
depth : $('#cubeiq_wdth').text(),
weight : $('#cubeiq_wght').text()
},
{
...
}
];
then you can loop:
$.each(array, function() {
alert(this.height + ' ' + this.length + ...);
});
And to achieve what you want to achieve (loop through the properties of an object) you could do this:
for (var propertyName in export_pkg) {
alert(propertyName + ' ' + export_pkg[propertyName]);
}
your object has the property length
which $.each
uses to iterate over the array. Since you are defining it, you are screwing up the behavior of the method. Try changing the name to something else like _length
var export_pkg = { height : '10', _length : '3', depth : '30', weight : '40' };
精彩评论