I'm fairly new to javascript professionally and I've encountered a situation where I need to supply unique ids to every element in a 2D array programmatically. I asked this question before but I made the mistake of not specifying how the array is structured and received an answer appropriate to a 1d array. My array is structured as follows and it would be great to know how to create unique ids for every element within the array:
var startRow = Math.floor(scroll.x / alpha.width);
var startCol = Math.floor(scroll.y / alpha.height);
var rowCount = startRow + Math.floor(canvas.width / alpha.width) + 2;
var colCount = startCol + Math.floor(canvas.height / alpha.height) + 2;
rowCount = ((startRow + rowCount) > grid.width) ? grid.width : rowCount;
colCount = ((startCol + colCount) > grid.height) ? grid.height : colCount;
for (var row = startRow; row < rowCount; row++) {
for (var col = startCol; col < colCount; col++) {
var tilePositionX = alpha.width * row - 25;
var tilePositionY = alpha.height * col + 45;
Many thanks
Also, here is the previous response I received: JavaScript array id loop
Like your last question said, why don't you just refer to the index - it's totally unique. A 2D array would have [i][j]
indices, which can't be occupied by more than one item.
var startRow = 0;
var startCol = 0;
var rowCount = 10;
var colCount = 5;
var someArray = [];
for (var row = startRow; row < rowCount; row++) {
someArray[row] = [];
for (var col = startCol; col < colCount; col++) {
someArray[row][col] = row + ' ' + col;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.