控制台说我有错误



我的代码正常工作,但是当我在Google Chrome上选中控制台时,我会遇到错误。出于好奇,我真的很想知道这意味着什么,因为代码似乎正常。

我的代码:

var images = [];
var imageIndex = 0;
var $mainImage = $(".thumb-large img");
var $mainCaption = $(".thumb-large p");
var $thumbnails = $(".thumbnails img");
//var $mainName = $(".thumb-large-descrip p.name")

function showImage(index) {
  $mainImage.attr({src: images[index].source});// this is where the error is showing
  $mainCaption.text(images[index].caption);
  $mainImage.attr({name: images[index].artistName});
}

我将代码的片段提供给了该错误。以下是Google Chrome Console所说的:

undurew typeerror:无法读取未定义的属性

的属性"源"

只是查看有关这意味着什么的建议???让我知道您是否需要更多信息。

数组var images = [];不包含任何元素。

如果您的数组为var arr = ['a','b','c'],并且您尝试访问arr[5],则它将返回undefined。这就是这里发生的事情。

将一些数据添加到您的数组中。

在您的情况下,看起来像:

var images = [
  { source: 'http://placehold.it/350x150',
    caption: 'This thing',
    artistName: 'troy beckett'
  },
  { source: 'http://placehold.it/250x250',
    caption: 'Another thing',
    artistName: 'troy beckett'
  }
];

您需要在尝试访问索引上的图像是否存在。您可以做:

function showImage(index) {
  if(images.length > index) { //This checks that something exists at that index and only if it exists does the following code run
    $mainImage.attr({src: images[index].source});
    $mainCaption.text(images[index].caption);
    $mainImage.attr({name: images[index].artistName});
  } else {
    console.log("Tried to access a nonexistent image at index: " + index)
  }
}

相关内容

最新更新