javascript - 类型错误 : foo is undefined when trying to call it in array

标签 javascript arrays for-loop

我有这个小方法。

$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/

相关文章:

javascript - 这段 JavaScript 的语法错误在哪里?

javascript - 加载 React Native 后渲染 RSS 提要数据

c - C 中的随机字母 [段错误]

c++ - 对 N 个不同大小的数组的每个元素应用相同的函数

javascript - 无论 promise 是否兑现,如何执行相同的操作?

javascript - highcharts 中的数千个运算符

javascript - NodeJs 从 MySQL 查询结果创建新数组

python - 使用 Django 存储整数数组

javascript - 在子函数中访问循环迭代?

java - java中的for循环