[英]error while trying to put values into an array using jquery each() function
I have this code: 我有以下代码:
$(".categoty-add").each(function(i) {
categories[i][0] = $(this).val();
});
And in output i get 在输出中我得到
TypeError: can't convert undefined to object
categories[i][0] = $(this).val();
This is my array: 这是我的数组:
var categories = new Array(2);
for (i = 0; i < categories . length; ++ i)
categories [i] = new Array (2);
What's wrong? 怎么了?
There has to be two textbox with class category-add
. 必须有两个带有class
category-add
文本框。 it they are more than two then you iterator i will be assigned a value >= 2 and then you statement becomes 如果它们大于两个,则为您的迭代器分配一个值> = 2,然后您的语句变为
categories[2][0] = $(this).val();
which is out of the bounds of the array. 这超出了数组的范围。
To dynamically create an array ( first time code is run), and later update it you can do this: 要动态创建一个数组(第一次运行代码),然后对其进行更新,可以执行以下操作:
/* 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()];
}
});
DEMO: http://jsfiddle.net/FFQ2s/ 演示: http : //jsfiddle.net/FFQ2s/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.