简体   繁体   English

在JavaScript中创建多维数组

[英]Create multidimensional array in javascript

I would like to create a multidimensional javascript array like this : 我想创建一个这样的多维javascript数组:

array('cats' => array(
    'cat_1' => array(1, 2, 3 ...)
    ), array(
    'cat_2' => array(....

I would like to add/remove "cat_id" and "tag_id" according to my variables... 我想根据我的变量添加/删除“ cat_id”和“ tag_id” ...

var filter = {cats : [[]]};

function generateArray(cat_id, tag_id, add = true){
  if(add == true)
    filter.cats = [cat_id];
    filter.cats[cat_id].push(tag_id);
  } else {
    //How to delete record the tag_id ?
    //filter[cats][cat_id].(tag_id);
  }
  return filter;
}

generateArray(1, 1, true);
generateArray(2, 2, true);
generateArray(2, 3, true); etc...

I have this error message : 我有此错误消息:

undefined is not object (evaluating filter.cats[cat_id].push 未定义不是对象(评估filter.cats [cat_id] .push

What's wrong ? 怎么了 ? Thanks in advance. 提前致谢。

The problem in this code: 此代码中的问题:

filter.cats = [cat_id];
filter.cats[cat_id].push(tag_id);

is that in the first line you set filter.cats to become an array with one element cat_id (on index 0). 是在第一行中,将filter.cats设置为具有一个元素cat_id (在索引0上)的数组。 Then in the second line you try to access an element in that array with the index cat_id (not the value cat_id) which does not exists or is a number when cat_id is zero. 然后,在第二行中,尝试使用索引cat_id (而不是值cat_id)访问该数组中的元素,该元素不存在或当cat_id为零时为数字。 Once you try to use the element as an object (by calling push on it) you get this error. 一旦尝试将元素用作对象(通过调用push),就会收到此错误。

Instead of those two lines you could write 代替这两行,您可以编写

if (typeof filter.cats[cat_id] == 'undefined') 
  filter.cats[cat_id] = [tag_id]; // initialize element as an array object
else
  filter.cats[cat_id].push(tag_id);  // already initialized, so push

Here is some code to give you an example of how you may achieve your goal: 以下代码为您提供了一个示例,说明如何实现目标:

function addCatTag(cats, cat_id, tag_id) {
    var cat = cats[cat_id];
    if (typeof cat == 'undefined') {
        cats[cat_id] = [tag_id];
    } else {
        cat.push( tag_id );
    }
}

function removeCatTag(cats, cat_id, tag_id) {
    var cat = cats[cat_id];
    if (typeof cat != 'object') 
        return;
    var tag_idx = cat.indexOf(tag_id);
    if (tag_idx >= 0) {
      cat.splice(tag_idx, 1);
    }       
}

var cats = {};
addCatTag(cats, 'felix', 1);
addCatTag(cats, 'felix', 2);
addCatTag(cats, 'fluffy', 1);
removeCatTag(cats, 'felix', 2);

alert( JSON.stringify(cats) );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM