The issue is that selectedItems is an array counting from 0; if there were 3 elements, you would access them by array[0], array[1], array[2]. So, you want the 'for' loop to count one less than the array length.
What's happening now is that it's doing array[0], array[1], array[2], and then it's trying to do array[3] but there isn't any! Because of the <=.
Check out this link for more info on arrays in javascript.