Meaningless Drivel is fun!*
The moose likes HTML, CSS and JavaScript and the fly likes Having trouble with splice and unshift. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » HTML, CSS and JavaScript
Bookmark "Having trouble with splice and unshift. " Watch "Having trouble with splice and unshift. " New topic
Author

Having trouble with splice and unshift.

Neil Cartmell
Ranch Hand

Joined: Feb 13, 2010
Posts: 150
Hello. Today I've been making a tetris game. I'm now writing the code, that checks to see if the player has made a line.

The removeLine method takes an array of arrays called grid. The row is the row of the grid that I'm removing. I want to clear that row by setting every element to zeros then take it from the grid and place it at the top again. I have now got it to work using the method below. But here I pass a new array. You see the line I have commented out? If instead of creating a new array I use the array returned by splice it doesn't work at all. It seems to place the entire array into grid[0][0]. So grid [0][0] = 0, 0, 0, 0, 0, 0, 0, 0. Where it should just be = 0. I can't understand why. I've printed out the values returned by splice and it is the same as the values I end up putting back in the with the new array.

Maybe I've been at it too long, but I can't seem to see what I'm doing that's different. Can anyone help?


Neil Cartmell
Ranch Hand

Joined: Feb 13, 2010
Posts: 150
Just some more info in case anyone wants to try and help me solve this.

The variable named line, when printed out in an alert, reads "0, 0, 0, 0, 0, 0, 0, 0". line[0] reads the same thing. Yet line[1] = undefined. line.length = 1.

I thought splice retuns an array? It reads like an array, but it's not letting me use it like one. I know I'm missing something silly.
Neil Cartmell
Ranch Hand

Joined: Feb 13, 2010
Posts: 150
Ok I found out what the problem is. I should have put this..

var line = grid.splice(row, 1)[0];

Because it returns an array of the deleted elements. So in this case an array where the array I just deleted was at the 0 index. Phew! The best way to solve a bug is to post in a forum then just after you post you'll work out the answer!
Neil Cartmell
Ranch Hand

Joined: Feb 13, 2010
Posts: 150
However as it's just returning a new array, there is no point using the returned array rather than just creating a new one. At least I know what is going on now.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Having trouble with splice and unshift.
 
Similar Threads
Multidimensional Array Nightmare!
Could you please help me?
Tile constraints
2-Dimensional Arrays?
checking for neighbours in array