Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 尝试使用jquery each()函数将值放入数组时出错_Javascript_Jquery_Each - Fatal编程技术网

Javascript 尝试使用jquery each()函数将值放入数组时出错

Javascript 尝试使用jquery each()函数将值放入数组时出错,javascript,jquery,each,Javascript,Jquery,Each,我有以下代码: $(".categoty-add").each(function(i) { categories[i][0] = $(this).val(); }); 在输出中,我得到 TypeError: can't convert undefined to object categories[i][0] = $(this).val(); 这是我的阵列: var categories = new Array(2); for (i =

我有以下代码:

$(".categoty-add").each(function(i) {
            categories[i][0] = $(this).val();
    });
在输出中,我得到

TypeError: can't convert undefined to object    
categories[i][0] = $(this).val();
这是我的阵列:

    var categories = new Array(2);
    for (i = 0; i < categories . length; ++ i)
    categories [i] = new Array (2);
var类别=新数组(2);
对于(i=0;i

怎么了?

必须有两个文本框,其中class
category add
。若它们大于2,那个么迭代器i将被赋值>=2,然后语句变为

categories[2][0] = $(this).val();

超出数组的界限。

要动态创建数组(第一次运行代码)并在以后进行更新,可以执行以下操作:

/* create empty array, syntax is shortcut for new Array() and just as efficient*/
var categories=[];

$(".categoty-add").each(function(i) {
   if( categories[i] ){ /* if doesn't exist will be undefined and trigger "else"*/
        /* sub array exists, just update it*/
        categories[i][0] = $(this).val();
    }else{ 
        /* create new sub array and give value to first position */
        categories[i] =[ $(this).val()];
    }
});

演示:

类别所标识的元素类型是什么?它们是否有值属性(对于ex:input)?来自texbox的值,迭代器有一些问题,因为如果我将类别[I][0]中的I替换为f.ex1,它就起作用了。您没有检查类别数组是否有I索引,是否确定类别数组的长度等于或大于.categoty添加项目的数量?您可能有比数组更多的元素。有两个文本框包含此项class@user1776165:如果这三个答案都不能满足您的需要,请留下评论,如果其中任何一个答案是正确的,得到答案后不要走开,返回并将其标记为答案。使用alert检查“$(this).val()”的值。它可能返回未定义。