【发布时间】:2017-06-08 07:03:36
【问题描述】:
在我的一个项目中,我使用 API 从其他网站获取数据,但要获取所有数据,我需要编写 8 个相同代码块,但只有两个不同的变量。所以很明显我想定义函数并使用它。
函数有两个参数,一个是对象,另一个是id。在函数内部,我循环遍历对象以使用 object.length 获取我需要的所有数据。循环在函数定义中执行,我在控制台中收到Uncaught TypeError: Cannot read property 'length' of undefined 错误。
这是我的代码:
function listAll(objectProp, destination) {
for (var i = 0; objectProp.length > i; i++ ) {
var option = document.createElement("option");
var value = document.createTextNode(objectProp.name);
option.appendChild(value);
document.getElementById(destination).appendChild(option);
}
}
我一直在寻找解决方案,但找不到同样的问题。谁能向我解释为什么会这样?
谢谢!
更新: 这就是代码的样子。
function listAll(objectProp, destination) {
if ( typeof(objectProp) != 'undefined' ) {
for (var i = 0; objectProp.length > i; i++ ) {
var option = document.createElement("option");
var value = document.createTextNode(objectProp[i].name);
option.appendChild(value);
document.getElementById(destination).appendChild(option);
}
}
}
感谢您的帮助!
【问题讨论】:
-
确保您传递给函数的变量实际上是实例化的并且不是
undefined,在调用函数之前将第一个参数记录到控制台 -
你可以做一个简单的检查
if(typeof(objectProp) != 'undefined') { } -
谢谢大家!它有帮助!我之前尝试过,但后来什么也没发生。原来我在调用函数时丢失了字母!
标签: javascript function loops