I am brand new to JavaScript and still figuring out the way things interact, so I apologize if this is obvious. I am ultimately trying to create a sliding tile puzzle, but at the moment I need to create a 2 dimensional array that will populate my grid with values (1-8). Basically all of my information thus far has been gathered from internet searches as my other resources have proven to be pretty useless.
Here is my code that generates a grid:
function newPuzzle(r, c)
{
var table = document.createElement("table");
for (var i = 0; i < r; i++)
{
var row = document.createElement('tr');
for (var j = 0; j < c; j++)
{
var column = document.createElement('td');
if (i%2 == j%2)
{
column.className = "even";
}
else
{
column.className = "odd";
}
row.appendChild(column);
}
table.appendChild(row);
}
document.body.appendChild(table);
populateTable();
}
At the end I've called the populateTable() function (which I'm not even sure will work) and here is the code for that:
function populateTable()
{
var cell = new Array(_r);
for (var i = 0; i < _r; i++)
{
cell[i] = new Array(_c);
}
for (var i = 0; i < cell.length; ++i)
{
var entry = cell[i];
for (var j = 0; j < entry.length; ++j)
{
var gridTable = document.getElementByTagName("table");
var _cells = gridTable.rows[i].cells[j].innerHTML = "2";
//the 2 is just for testing
}
}
}
Any insight would be very appreciated.
Your code basically had two issues, when I ran it:
In your method populateTable() the variables _r and _c were not defined, so I passed them in as arguments.
The method document.getElementByTagName does not exists, it's plural document.getElementsByTagName which in turn returns an array of all <table> elements so you have to select which one you want - I opted for the first one since I assume you only have one table on your page.
Here are the changes:
function newPuzzle(r, c)
{
var table = document.createElement("table");
for (var i = 0; i < r; i++)
{
var row = document.createElement('tr');
for (var j = 0; j < c; j++)
{
var column = document.createElement('td');
if (i%2 == j%2)
{
column.className = "even";
}
else
{
column.className = "odd";
}
row.appendChild(column);
}
table.appendChild(row);
}
document.body.appendChild(table);
// here we pass _r and _c as arguments
populateTable(r,c);
}
function populateTable(_r,_c)
{
var cell = new Array(_r);
for (var i = 0; i < _r; i++)
{
cell[i] = new Array(_c);
}
for (var i = 0; i < cell.length; ++i)
{
var entry = cell[i];
for (var j = 0; j < entry.length; ++j)
{
// getElementsByTagName returns an array of all table elements
var gridTable = document.getElementsByTagName("table");
// we select the first table element with the array index [0]
var _cells = gridTable[0].rows[i].cells[j].innerHTML = "2";
//the 2 is just for testing
}
}
}
An interactive JS fiddle: https://jsfiddle.net/Ls76kk2a/2/
An optimization tip: Give your table a unique ID like this:
var table = document.createElement("table");
table.id = "mySuperCoolTable";
Then you can be sure you get the right one with:
var gridTable = document.getElementById("mySuperCoolTable");
This only returns one (or none) table because the ID must be unique.
Response to your comment:
Here's an example how to populate all elements but the last one:
function populateTable(_r,_c)
{
var cell = new Array(_r);
for (var i = 0; i < _r; i++)
{
cell[i] = new Array(_c);
for (var j = 0; j < _c; j++) {
cell[i][j] = i*_c + j;
}
}
// fix the last one
cell[_r-1][_c-1] = "X";
for (var i = 0; i < cell.length; ++i)
{
var entry = cell[i];
for (var j = 0; j < entry.length; ++j)
{
var gridTable = document.getElementsByTagName("table");
var _cells = gridTable[0].rows[i].cells[j].innerHTML = cell[i][j];
}
}
}
And here's the JS fiddle: https://jsfiddle.net/Ls76kk2a/3/
Related
I want to predefine the 2d-array containing an array of objects like this below image:
I am trying this way:
var grid = [];
iMax = 3;
jMax = 2;
count = 0;
for (let i = 0; i < iMax; i++) {
grid[i] = [];
for (let j = 0; j < jMax; j++) {
grid[i][j] = count;
count++;
}
}
In your code you're building up the two-dimensional array, but you are filling the rows with numbers (i.e. your setting the count) instead of an array of objects. So if you want to achieve the exact same structure as provided in the screenshot, you can do:
const rows = 4;
const cols = 4;
const elementCount = 3;
function buildGrid(rows,cols, elementCount) {
const grid = [];
for(let i=0; i < rows; i++) {
grid[i] = [];
for(let j=0; j < cols; j++) {
grid[i].push(Array.from({length:elementCount}, () => ({})));
}
}
return grid;
}
const grid = buildGrid(rows,cols,elementCount);
console.log(grid);
I am trying to create and initialize a bidimensional array in javascript inside an AngularJS application as follows:
$scope.invalidVote = [];
for (var i = 0; i < $scope.arry1.length; i += 1) {
$scope.answersCount[i] = $scope.arry1[i].arry2.length;
for(var j = 0; j < $scope.arry1[i].arry2.length; j += 1) {
$scope.invalidVote[i][j] = false;
}
}
But it doesn't work, What is the right way to do that?
try this:
$scope.invalidVote = [];
for (var i = 0; i < $scope.arry1.length; i++) {
$scope.answersCount[i] = $scope.arry1[i].arry2.length;
$scope.invalidVote[i] = [];
for(var j = 0; j < $scope.arry1[i].arry2.length; j++) {
$scope.invalidVote[i][j] = false;
}
}
I'm assuming $scope.arry1[i] is an array that contain other arrays and is already fill with values.
So your code should look like:
$scope.invalidVote = $scope.arry1;
for (var i = 0; i < $scope.arry1.length; i += 1)
{
$scope.answersCount[i] = $scope.arry1[i].length;
for(var j = 0; j < $scope.arry1[i].length; j += 1)
{
$scope.invalidVote[i][j] = false;
}
}
'$scope.invalidVote = $scope.arry1;' declaring "invalidVote" like this ensure it contains the same amount of indexes.
I am writing a function which should create a 2 dimensional array pre-populated with zeros. My output looks correct, but apparently there is a bug in it that I am not seeing. Does anybody know what it is? I don't see it.
function createMatrix(size) {
var defValue = 0;
var row = [];
var matrix = [];
for (var i = 0; i < size; i++) {
row.push(defValue);
}
for (var i = 0; i < size; i++) {
matrix.push(row);
}
return matrix;
}
You're pushing the same row into your array matrix every time. These all point to the same array, since they are passed by reference.
You should make a new array for each row instead:
function createMatrix(size){
var defValue = 0;
var matrix = [];
for (var i = 0; i < size; i++) {
var row = [];
for (var j = 0; j < size; j++) {
row.push(defValue);
}
matrix.push(row);
}
return matrix;
}
The problem lies in the second loop;
If you stop and trace your code, you can see that you are only creating one "row" array whereas you most likely want to make size amount of rows.
Your code should probably look like this
var matrix = [];
for(var i = 0; i < size; i++) {
//temp row to append to array
var row = [];
//fill row array with 0s
for (var j = 0; j < size; j++) {
row.push(0);
}
//append row to the matrix
matrix.push(row);
}
return matrix
This way you are pushing a completed row at the end of each iteration.
I have the following code
for(i = 0; i < num; i++) {
var yPos = 10*i;
var numCells = wid/30;
for(j = 0; j < numCells; j++) {
blocks[i][j] = 1;
}
}
With
blocks = new Array();
However, when I execute the code I receive an error stating that:
can't convert undefined to object
Any ideas? :/
var blocks = [];
for(i = 0; i < num; i++) {
var yPos = 10*i;
var numCells = wid/30;
blocks[i] = []; // here is a fix
for(j = 0; j < numCells; j++) {
blocks[i][j] = 1;
}
}
In your particular case, since all the rows are initialised to be the same (a series of 1s), you can also do
var blocks = new Array(),
blockRow = new Array();
for (var i = 0; i < numCells; i++) {
blockRow.push(1);
}
for (var i = 0; i < num; i++) {
blocks.push(blockRow.slice()); // slice() makes a copy of blockRow
}
I am trying to sort a table with JavaScript.
function test() {
var table = document.getElementById("myTable");
var allRow = table.getElementsByTagName('tr');
var ar = new Array();
for(var i = 1; i < allRow.length; i++) {
ar[i - 1] = allRow[i];
}
//sort the data according to number
ar.sort(function(l, r) {
var num1 = parseInt(l.childNodes[1].innerHTML);
var num2 = parseInt(r.childNodes[1].innerHTML);
return (num1 > num2) ? 1 : ((num1 < num2) ? -1 : 0);
});
//assigning the sorted data in the table
for(var i = 0; i < ar.length; i++) {
allRow[i + 1].innerHTML = ar[i].innerHTML;
}
}
But when I am trying to assigning the sorted data in the table somehow it does not. But If I keep the ar data in a new array and then assign that in allRow it does. I am totally newbie in this. So can anyone please tell me why is this happening?
var tmp = new Array();
for(var i = 0 ; i<ar.length ; i++){
tmp[i] = ar[i].innerHTML;
}
for(var i = 0; i < ar.length; i++) {
allRow[i + 1].innerHTML = tmp[i];
}
When you copy the elements to the ar array you are not making copies of the elements, you are only copying the references to the elements. The ar array doesn't contain elements with the same content as the allRow array, it contains the same elements.
When you change the content of an element in the allRow array, it will change in the ar array also, as it's the same element.
When you have sorted the array, read the innerHTML from all rows, then you can write them back:
for(var i = 0; i < ar.length; i++) {
ar[i] = ar[i].innerHTML;
}
for(var i = 0; i < ar.length; i++) {
allRow[i + 1].innerHTML = ar[i];
}
why u r override sort function with your own.When sort give functionality of sorting any kind of data like numeric , alphabetical an etc...
make it simple like this
function test() {
var table = document.getElementById("myTable");
var allRow = table.getElementsByTagName('tr');
var ar = new Array();
for(var i = 1; i <= allRow.length; i++) {
ar[i-1]=table.rows[i-1].cells[0].innerHTML;
}
ar.sort();
//assigning the sorted data in the table
for(var i = 1; i <= allRow.length; i++) {
table.rows[i-1].cells[0].innerHTML=ar[i-1];
}
}