Abnormal issues with pushing data into an array
sub addToList() matched = false countIndex = 0 if m.global.watchList.Count() > 0
m.movieArray = m.global.watchList for each item in m.global.watchList if item.TITLE = m.selectedMovie.TITLE m.movieArray.delete(countIndex) m.global.watchList = m.movieArray matched = true else m.movieArray.push(m.selectedMovie) m.global.watchList = m.movieArray matched = false end if if matched then EXIT FOR countIndex = countIndex + 1 end for else m.movieArray.push(m.selectedMovie) m.global.watchList = m.movieArray end if end sub
I am practicing and simulating an actual watchlist array. The issue with the code here is; after adding two movies to the watchList (which works fine), when I add a third one, it adds it twice, and when I add a fourth one, it adds it four times, and so on.
What am I doing wrong with the logic?
Thanks.
Mixing "for each" and indices is a bad idea, but that's only part of the problem. You're going to be pushing something every time the title doesn't match as you go through the loop. If I'm following what you're trying to do you should do something like:
for i = 0 to m.global.watchList.Count() - 1 if m.global.watchList[i].title = m.selectedMovie.TITLE then m.global.watchList.delete(i) exit for end if end for if i = m.global.watchList.Count() then m.global.watchList.Push(m.selectedMovie)
You could also use a matched flag, but if i is past the end of the watchList at the end of the for loop then it wasn't matched.
A note about your code: using m.movieArray isn't really accomplishing anything. Setting it equal to m.global.watchList doesn't create a copy of it, just another reference to the same data. Take this example:
x = [1,2,3] y = x y.delete(1) print x print y
It will give:
<Component: roArray> = [ 1 3 ] <Component: roArray> = [ 1 3 ]