Home > Net >  Why can't I access the array item without using an "if" function
Why can't I access the array item without using an "if" function

Time:04-03

I keep getting the error

"Cannot read properties of undefined (reading '2') at script.js:18:47" 

unless I put it in an if function.

Here's the array

['title','title',new Date("2022-03-26T10:00:00-06:00"),new Date("2022-04-02T10:00:00-06:00")],
['title','title',new Date("2022-04-02T10:00:00-06:00"),new Date("2022-04-09T10:00:00-06:00")],
['title', 'title', new Date("2022-04-09T10:00:00-06:00"), new Date("2022-04-16T10:00:00-06:00")],
['title', 'title', new Date("2022-04-16T10:00:00-06:00"), new Date("2022-04-23T10:00:00-06:00")],
['title', 'title', new Date("2022-04-23T10:00:00-06:00"), new Date("2022-04-30T10:00:00-06:00")],
['title', 'title', new Date("2022-04-30T10:00:00-06:00"), new Date("2022-05-07T10:00:00-06:00")],
['title', 'title', new Date("2022-05-07T10:00:00-06:00"), new Date("2022-05-14T10:00:00-06:00")],
['title', 'title', new Date("2022-05-14T10:00:00-06:00"), new Date("2022-05-21T10:00:00-06:00")],
['title', 'title', new Date("2022-05-21T10:00:00-06:00"), new Date("2022-05-28T10:00:00-06:00")]
];

Doesn't Work:

var today = Date.now();
var weeksPassed = Math.floor((today - Date.parse(nextRelease))/(24*3600*1000*7));
var latestRelease = episodeList[weeksPassed][2];
var nextRelease = episodeList[weeksPassed][3];
document.getElementById("previousEpisode").innerHTML = episodeList[weeksPassed][0];
document.getElementById("nextEpisode").innerHTML = episodeList[weeksPassed][1]

Works:

var nextRelease = new Date("2022-03-26T10:00:00-06:00");
var today = Date.now();
if (today > nextRelease) {
  var weeksPassed = Math.floor((today - Date.parse(nextRelease))/(24*3600*1000*7));
  latestRelease = episodeList[weeksPassed][2];
  nextRelease = episodeList[weeksPassed][3];
  document.getElementById("previousEpisode").innerHTML = episodeList[weeksPassed][0];
  document.getElementById("nextEpisode").innerHTML = episodeList[weeksPassed][1]
};

CodePudding user response:

im not very good at JavaScript, but i think youre using next release without initializing it properly so an exception is thrown down the line that cascades from that

  • Related