繁体   English   中英

Javascript Uncaught TypeError:无法读取未定义的属性“ length”(使用数组)

[英]Javascript Uncaught TypeError: Cannot read property 'length' of undefined (using an array)

我有一个数组设置,它将两个参数传递给函数。 但是,当我使用console.log时,出现异常。 奇怪的是,如果我要从参数中删除参数,它将运行,这是他们的任何原因吗,我该如何解决?

var musicians = ["Paul", "John", "Yuri"];

var instruments = ["Drums", "Guitar", "Chelo"];

function theBeatlesPlay(musicians, instruments) {

    var empty = [];

    for (var i = 0; i < **musicians.length**; i++) {

      var str = musicians[i] + " plays " + instruments[i];
      empty = str;
      **console.log(empty)**;
    }
    }

    theBeatlesPlay();

您必须在调用函数时将参数传递给函数。

theBeatlesPlay(musicians, instruments);

 var musicians = ["Paul", "John", "Yuri"], instruments = ["Drums", "Guitar", "Chelo"]; function theBeatlesPlay(musicians, instruments) { var empty = []; for (var i = 0; i < musicians.length; i++) { var str = musicians[i] + " plays " + instruments[i]; empty = str; console.log(empty); } } theBeatlesPlay(musicians, instruments); 

您的问题是您没有将参数传递给函数。 使用函数的正确方法是,首先是调用函数的代码,然后是函数。 如果您使用更多功能,则会失去对工作的跟踪,或者更糟的是会开始出错,

 var musicians = ["Paul", "John", "Yuri"]; var instruments = ["Drums", "Guitar", "Chelo"]; var errlog = theBeatlesPlay(musicians, instruments); console.log(errlog); function theBeatlesPlay(musicians_val, instruments_val) { var empty = []; for (var i = 0; i < musicians_val.length; i++) { var str = musicians_val[i] + " plays " + instruments_val[i]; empty = str; } return empty; } 

说明:在声明带有参数的函数时,这些参数将成为局部参数。 这意味着,即使您有一些名称为musicians and instruments变量,函数中具有相同名称的参数仍将被视为局部变量。

要解决您的问题,您有两种方法:

  1. 删除函数声明语句中的参数(原来您想访问那些在函数外部声明的变量,因此您不需要为函数使用参数):

     var musicians = ["Paul", "John", "Yuri"], instruments = ["Drums", "Guitar", "Chelo"]; /* Precondition: defined musicians and instruments arrays outside of a function */ function theBeatlesPlay(/* No params */) { var empty = []; for (var i = 0; i < musicians.length; i++) { var str = musicians[i] + " plays " + instruments[i]; empty = str; console.log(empty); } } 
  2. 调用传递给它的函数,该函数先前声明了两个数组:

     /* musicians and instruments variables are LOCAL for the function in this case */ function theBeatlesPlay(musicians, instruments) { var empty = []; for (var i = 0; i < musicians.length; i++) { var str = musicians[i] + " plays " + instruments[i]; empty = str; console.log(empty); } } theBeatlesPlay(musicians, instruments); 

我也强烈建议您不要命名为empty变量,因为最初它是空的。 否则,它应该是一个常数。

顺便说一句,分析抛出什么类型的异常以及它提供什么消息是很有用的。

暂无
暂无

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

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