开发者问题收集

Javascript 未捕获的类型错误:无法读取未定义的属性“length”(使用数组)

2017-04-15
2569

我设置了一个数组,它将两个参数传递给函数。但是,当我使用 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();
3个回答

调用函数时,必须将参数传递给该函数。

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);
kind user
2017-04-15

解释:当您声明带有参数的函数时,这些参数将成为本地参数。这意味着,即使您有一些名为 musiciansinstruments 的变量,函数中具有相同名称的参数仍将被视为 本地

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

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

    var musicals = ["Paul", "John", "Yuri"],
    instruments = ["Drums", "Guitar", "Chelo"];
    
    /* 前提条件:在函数外部定义 musicals 和 musicals 数组 */
    function theBeatlesPlay(/* 无参数 */) {
    
    var empty = [];
    
    for (var i = 0; i < musicals.length; i++) {
    
    var str = musicals[i] + " plays " + musicals[i];
    empty = str;
    console.log(empty);
    }
    }
    
  2. 调用函数,将之前声明的两个数组传递给它:

    /*
    在这种情况下,musicians 和 musicals 变量是函数的本地变量
    */
    function theBeatlesPlay(musicians, musicals) {
    
    var empty = [];
    
    for (var i = 0; i < musicals.length; i++) {
    
    var str = musicals[i] + " plays " + musicals[i];
    empty = str;
    console.log(empty);
    }
    }
    
    theBeatlesPlay(musicians, musicals);
    

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

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

Dzmtrs
2017-04-15

您的问题是您没有将参数传递给函数。 使用函数的正确方法是首先调用函数的代码,然后是函数。如果您使用更多函数,您将忘记自己在做什么,或者更糟的是会开始出现错误,

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;
 }

    
Jose Marques
2017-04-15