我有这个小方法。
$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
。您可以简单地替换<=
与 <
在循环的终止条件中,它应该可以正常工作。
关于javascript - 类型错误 : foo is undefined when trying to call it in array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48469055/