[英]getting javascript error while iterating through array
function sortproducts(filprodlist)
{
var prod;
var k = 0;
for (i = 0; i < filprodlist.length; i++) {
var k = i + 1;
var p=filprodlist[i].EntityKey.substr(filprodlist[i].EntityKey.length - 1);
var p2=filprodlist[k].EntityKey.substr(filprodlist[k].EntityKey.length - 1);
if ( p>p2) {
temp = filprodlist[k];
filprodlist[k] = filprodlist[i];
filprodlist[i] = temp;
}
}
rederProduct(filprodlist);
}
while executing above code getting following error TypeError: filprodlist[k] is undefined 在执行上述代码时,出现以下错误TypeError:filprodlist [k]未定义
Reason 原因
On last iteration, when i
is at last element of array. 在最后一次迭代中,当i
位于数组的最后一个元素时。 You are fetching are using var k = i + 1;
您正在使用var k = i + 1;
, where k
doesn't exists. ,其中k
不存在。 Thus you are getting the error. 因此,您会得到错误。
So Use 所以用
for (i = 0; i < filprodlist.length - 1; i++) {
instead of 代替
for (i = 0; i < filprodlist.length; i++) {
Let's say filprodlist
has 10 items. 假设filprodlist
有10个项目。 Then the items are indexed 0-9 and Your i
goes through 0-9. 然后将这些项目索引为0-9,而您的i
会经历0-9。 In every iteration You define k = i + 1
. 在每次迭代中,您都定义k = i + 1
。 So in the last iteration i = 9
, k = 10
and You are trying to access filprodlist[10]
which doesn't exist (returns undefined
). 因此,在上一次迭代中, i = 9
, k = 10
并且您试图访问filprodlist[10]
,该文件不存在(返回undefined
)。 Solution is in @Satpal's answer. 解决方案在@Satpal的答案中。
Don't var
inside loops, blocks don't have scope in JavaScript , var
every variable you want to use in one var
statement. 不要在循环内var
,在JavaScript中 ,块没有作用域, var
要在一个var
语句中使用的每个变量。 End your loop when the highest index reaches the end ( k
). 当最高索引到达结尾( k
)时结束循环。 You can move k
into the for
's iterate step because you're really iterating with this, too. 您可以将k
移至for
的迭代步骤,因为您也确实对此进行了迭代。
function sortproducts(filprodlist) {
var prod, i, k, p, p2, temp;
for (i = 0, k = 1; k < filprodlist.length; ++i, ++k) {
p = filprodlist[i].EntityKey.substr(filprodlist[i].EntityKey.length - 1);
p2 = filprodlist[k].EntityKey.substr(filprodlist[k].EntityKey.length - 1);
if (p > p2) {
temp = filprodlist[k];
filprodlist[k] = filprodlist[i];
filprodlist[i] = temp;
}
}
rederProduct(filprodlist);
}
A different way to do it is forget k
all together, start from i = 1
and use i - 1
and i
, this means you're iterating with less variables so it might be easier for you to follow the code in your mind. 一种不同的处理方式是一起忘记k
,从i = 1
开始并使用i - 1
和i
,这意味着您要使用较少的变量进行迭代,因此您可能更容易遵循自己的想法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.