Bogdan Rosciuc Bogdan Rosciuc - 11 months ago 53
Javascript Question

Javascript TypeError states a list is undefined

I created a function which receives a list as input and then operates on that list:

function selected_items(list) {
for (i=0;i<=list.length;i++){
item = list[i].split("-");
item_id = item[0] + '-' + item[1] + '-' + item[2]
user_id = item[4]
$('#shift_data_' + user_id).children('#' + item_id).toggleClass('selected')

The list is composed by some strings like this : ["a-b-c", "a1-b1-c1", etc.]

I want to process the strings one by one, split them after the operator "-" and then do some work on that to help me select some items in the DOM.

The funny part is that the code works as expected however in the console I get
the following error:

TypeError: list[i] is undefined
--> item = list[i].split("-");

Any ideas on why I'm getting this error even though the code is working?

Answer Source

You are looping the list out of range. Try changing this:

for (i=0;i<=list.length;i++){

by this:

for (i=0;i<=list.length - 1;i++){