ItsYaBoiWesley Posted August 16, 2018 Share Posted August 16, 2018 Hi! I'm trying to make a 2D array with a ton of zeroes. For some reason, this does not work. (By does not work, I mean I get errors when accessing the array. If I initialize the array manually, it's smooth sailing.) var blankRow = []; for(var x = 0; x < world[0].length; x++) { blankRow.push(0); } for(var y = 0; y < world.length; y++) { processedWorld.push(blankRow); } It pushes the blank row full of zeroes (the horizontal axis) then pumps that into the destination array (processedWorld, the vertical axis) What am I screwing up P.S. "world" is a different array from "processedWorld" and has already been defined, and works perfectly. Quote Link to comment Share on other sites More sharing options...
b10b Posted August 16, 2018 Share Posted August 16, 2018 Looks like you're pushing the same blankRow into all the rows. So any change to any row will effect all rows. Whereas you probably want to push a new bankRow into each row? Solution: move the x loop into the y loop. You may also want to consider an alternative data structure to an array if you're doing higher level manipulation. Quote Link to comment Share on other sites More sharing options...
ItsYaBoiWesley Posted August 17, 2018 Author Share Posted August 17, 2018 This worked, thanks! Quote Link to comment Share on other sites More sharing options...
mattstyles Posted August 18, 2018 Share Posted August 18, 2018 The most simple way is probably: const DIM = 100 const map = new Array(DIM).fill(0) For the 2D variant you're using: const X_SIZE = 4 const Y_SIZE = 2 const map = new Array(X_SIZE).fill(new Array(Y_SIZE).fill(0)) // Better: function createArray (length, fill) { return new Array(length).fill(fill) } const map = createArray(X_SIZE, createArray(Y_SIZE, 0)) Depending on your coordinate system you might want to invert X and Y. Note that fill is really naive, I normally use some other helpers that allow a 'fill' function to accept a function which allows a really nice clean API for creating simple or complex arrays. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.