$.each() 未正确迭代数组
我在使用 jQuery 迭代关联数组时遇到问题。我在 html 页面中有四个跨度...并且我使用 json 形成一个由 text() 值组成的数组,以构建维度数组
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);
});
出于某种原因,我无法弄清楚...export_pkg 的长度始终是数组内长度的文本值。 Firefox 和 IE 的开发工具都显示 export_pkg 是一个包含 4 个项目的数组,并且它具有正确的值。但是当我到达 $.each 块时...它忽略该对象并仅使用第二个条目作为对象的长度。
示例:如果数组具有 {length: 10},则无论其他值是什么,警报框都会出现 10 次。我一生都无法弄清楚为什么它没有像我预期的那样运行 4 次。
这是一个 jslint 链接 http://jsfiddle.net/fFDfU/
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/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,您使用的不是数组,而是一个对象。但是您可以根据需要使用
each
迭代对象属性。each
使用length
属性来查看需要迭代的项目数。由于对象中有一个length
,它会混淆each
。我建议您更改该属性名称: http://jsfiddle.net/ErickPetru/fFDfU/1/< /a>
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 byeach
to see how many items need to be iterated. Since you have alength
inside your object, it confuseseach
.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:
then you can loop:
And to achieve what you want to achieve (loop through the properties of an object) you could do this:
您的对象具有
length
属性,$.each
使用该属性来迭代数组。既然你定义了它,你就搞砸了该方法的行为。尝试将名称更改为其他名称,例如_length
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