1

我想创建数组filters_array,我在控制台中注意到的第一件事是 filter_group 无处可寻,这是保存对象的正确方法吗?

其次,在第二次单击时我希望数组增长,但此时它只是被覆盖了,我做错了什么?

  //
  var filters_array;

  //Ajax call to filter movies, grab them and reload container
  $(".option-set a").on("click", function(){

    var filter_value = $(this).data("filter-value");
    var filter_group = $(this).parents("ul").data("filter-group");

    filters_array = {filter_group : filter_value};
    console.dir(filters_array);

    $.ajax({
      url: templatePath + "getmovies.php",
      type: "GET",
      data: "",
      cache: false,
      success: function (data){
        console.dir("ajax call success!");
      }
    });

    return false;
  });
4

2 回答 2

0

I'd like to create array filters_array, first thing I noticed in console is that filter_group is nowhere to be found, is this a correct way to save objects?

Yes, it is the right way, but it is right that you can't see it from the console, it is declared inside the function's scope. But you can do this if you need to access it from the outside:

var filters_array, filter_value, filter_group; //hoisted here

  //Ajax call to filter movies, grab them and reload container
  $(".option-set a").on("click", function(){

    filter_value = $(this).data("filter-value");
    filter_group = $(this).parents("ul").data("filter-group");

    filters_array = {filter_group : filter_value};
    console.dir(filters_array);

    $.ajax({
      url: templatePath + "getmovies.php",
      type: "GET",
      data: "",
      cache: false,
      success: function (data){
        console.dir("ajax call success!");
      }
    });

    return false;
  });

Second, on second click I want array to grow, but at this point it is only overwritten, what am I doing wrong?

Well that's simple, you're initializing it again and again assigning it a new object every time, you have to do this:

filters_array[filter_group] = filter_value;

After having assigned to filters_array an empty object outside the function scope. Obviously you need to remove filters_array = {filter_group : filter_value}; and replace it with that line!

于 2013-06-17T09:09:33.943 回答
0

JavaScript 中的“关联数组”只是对象。我们通常称它们为“对象”或“映射”,以避免将它们与“数组”混淆(它们在 JavaScript中并不是真正的数组,但我们暂时忽略它)。

你想filters_array用一个空白对象初始化你:

var filters_array = {};

...然后在单击处理程序中,向其中添加一个条目,其中键是filter_group变量的值,值是filter_value变量中的值:

filters_array[filter_group] = filter_value;

因此,例如,如果filter_group有 value"foo"并且filter_value有 value "bar",你最终会得到一个属性 onfilters_array调用foovalue "bar"。然后,您可以通过多种方式访问​​该属性:

console.log(filters_array["foo"]); // "bar"
console.log(filters_array.foo);    // "bar"
var x = "foo";
console.log(filters_array[x]);     // "bar"

// Loop through all of the filter groups you've added
var key;
for (key in filters_array) {
     // here, `key` will be `"foo"` (for instance)
    console.log(filters_array[key]); // One of these will be "bar"
}
于 2013-06-17T09:06:34.497 回答