JavaScript的创建多维数组动态 [英] Javascript creating multidimensional array dynamically

查看:177
本文介绍了JavaScript的创建多维数组动态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这个现在strugling超过一天无法得到它的工作。我想创建一个认为必须pharsed到PHP的AJAX调用过滤变量的多维JavaScript数组。我们的目标是做一个产品过滤器和过滤掉不适用于过滤变量的产品。

I'm strugling with this for over a day now and can't get it working. I want to create a multidimensional javascript array that hold filter variables that must be pharsed to php for AJAX calls. The goal is to make a product filter and filter out products that don't apply to the filter variables.

最后一部分是PHP的,我知道如何解决。但我挣扎与创建包含所有选定的过滤变量的JavaScript数组。

The last part is php and I know how to solve that. But I'm struggling with creating a javascript array that holds all the selected filter variables.

我有一个过滤器_id filter_value_ID 。 Withing一个过滤器,例如大小,可以有像S,M,L,XL等不同的值

I have a filter_ID and a filter_value_ID. Withing a filter, for example size, there can be different values like S, M, L, XL etc.

所以,我想这样的一个数组:

So I want a array like this:

filterArr = array(
  [4] => array(10,20,30)
  [8] => array(4)
  [20] => array(2,3, 7)
)

当用户选中一个复选框,该数组必须填写。我设法它差不多,但问题是,我得到项目阵列中的,因为我不能在阵列中获得filterID。

The array must be filled when a user check a checkbox. I managed it almost, but the problem is that I'm getting null items in the array, because I cant get the filterID in the array.

我的code是对的jsfiddle: http://jsfiddle.net/VCfjp/

My code is on JSFiddle: http://jsfiddle.net/VCfjp/

在那里出错的部分是在第10行,11,12:

The part where it is going wrong is on line 10, 11, 12:

if (!(filterID in filter)) {
  filter[filterID] = [];
}

我跑停留在那一刻。我知道如何做到这一点在PHP,但不能让它在JavaScript工作。有些帮助是AP preciated! Offcourse我一直在看论坛上的其他线程,但找不到任何匹配。

I'm running stuck at the moment. I would know how to do it in PHP, but can't get it working in javascript. Some help is appreciated! Offcourse I've been looking at other threads on the forum, but can't find anything matching.

推荐答案

在JS数组哈希被定义为对象,因此使用它是这样的:

Hash arrays in JS are defined as object, so use it like this:

VAR对象= {
    4:[10,20,30],
    8:[4],
    20:[2,3,7]
};

只是观摩一下PHP将发行时输出继电器:

Just observe what PHP would ouput when issuing:

回声json_en code(阵列(
  [4] =>阵列(10,20,30)
  [8] =>阵列(4)
  [20] =>阵列(2,3,7)
));

您请求的code:

的jQuery(文件)。就绪(函数($){
    变种hashArray = {};
    $('。myCheckbox')。在('变化',函数(){
        VAR自我= $(本),
            checkboxId = parseInt函数(self.attr(数据ID)),因为你用它作为上述一系列//
            checkboxValue = parseInt函数(self.val()); //既然你也用它作为上述一系列
        如果(self.is(':检查')){
            //添加到阵列
            如果hashArray [checkboxId] = [](hashArray.hasOwnProperty(checkboxId)!);
            hashArray [checkboxId] .push(checkboxValue);
        }
        其他{
            如果(hashArray.hasOwnProperty(checkboxId)){
                //从数组中删除(如果存在)
                hashArray [checkboxId] .splice(hashArray [checkboxId] .indexOf(checkboxValue),1);
            }
        }
    });
});

这篇关于JavaScript的创建多维数组动态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆