.each()数组中的jQuery .each()数组

时间:2015-03-19 08:02:11

标签: jquery arrays each

听取对象数组

 advancedParams = [];
 advancedParams["cost"] = [];
 advancedParams["cost"]["from"] = 10;
 advancedParams["cost"]["to"] = 100;

但.each()没有看到第二个数组

 $.each(advancedParams, function( idx, obj ) {
     console.log(idx); // shows cost
     console.log(obj ); // shows [from: "10", to: "200"]
     $.each(obj, function( key, value ) {
         console.log(key); // nothing
         //each have no iterations, why?
     });
 }

2 个答案:

答案 0 :(得分:2)

这绝对无效:

{cost: [from: "10"], [to: "200"]}

因为在数组中,您不能将值:分开。

您应该分配一个对象,而不是声明一个数组[]

advancedParams = {};
advancedParams["cost"] = {};

查看下面的演示。



var advancedParams = {};
advancedParams["cost"] = {};
advancedParams["cost"]["from"] = 10;
advancedParams["cost"]["to"] = 100;

$.each(advancedParams, function(i, obj) {
  console.log(obj); // results in "Object {from: 10, to: 100}"
  $.each(obj, function(i, item) {
    console.log(item); // results in "10, 100"
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您的对象定义无效。请查看以下错误消息:

invalid object definition

将其存储在如下对象中:var obj = { from: 10, to:200}。或者,如果您想要一个对象数组,请执行以下操作:var arr =[{from:10,to:200},{from:1, to:300}]