【问题标题】:Loop inside function definition gets executed函数定义内的循环被执行
【发布时间】: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


【解决方案1】:

您无法在 JavaScript 中使用 .length 获取对象的长度。您将需要将数据存储在数组中或使用以下解决方案:Length of a JavaScript object

【讨论】:

  • 对不起,我不够具体。在该对象中有一个数组,我在其上使用 .length
猜你喜欢
  • 1970-01-01
  • 2013-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多