繁体   English   中英

TypeError:尝试在数组中调用foo时未定义

[英]TypeError: foo is undefined when trying to call it in array

我有这个小方法。

$cargos = JSON.parse('<?php echo $cargos ?>');
$html = '';

console.log($cargos[0][0]); //correct printing of the desired values

for(var x=0;x <= $cargos.length;x++)
{
   console.log(x); //this prints the numbers correctly
   $html += "<option value='"+$cargos[x][0]+"'>"+$cargos[x][1]+"</option>"; //error, $cargos[x] is undefined
}

我正在使用JSON从PHP检索一个(多维)数组,并且我打算对其进行一个小循环,但是由于出现错误,我在调用数组元素时不能使用变量x

TypeError: $cargos[x] is undefined

如果我尝试使用数字手动调用索引,它们将正确打印而不会出现错误。

我究竟做错了什么?

数组的索引在Javascript中从零开始。 因此,从头到尾遍历数组时,应从索引0遍历到length-of-array - 1 你可以简单的替换<=<在循环的终止条件,它应该工作的罚款。

暂无
暂无

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

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