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
}
Related
I am learning to use Javascript. I tried to fill an empty matrix, through a For cycle. I think that the sentence I declare has logic, and it should work, I have something intrigued. Anyone know the reason why Javascript does not work with this code?
I am learning to use Javascript. I tried to fill an empty matrix, through a For cycle. I think that the sentence I declare has logic, and it should work, I have something intrigued. Anyone know the reason why Javascript does not work with this code?
var i = 0 , j = 0;
var arr = [[],[]];
for( i = 0; i < 8; i++){
for( j = 0; j < 8; j++){
arr[i][j] = 7;
alert(arr[i][j]);
}
alert(arr[i][j]);
}
This should do what you are looking for.
var ar = new Array(10)
for(i = 0; i < 10; i++) {
ar[i] = new Array(10)
}
for(i = 0; i < 10; i++){
for(j = 0; j< 10; j++) {
ar[i][j] = 1
}
}
console.log(ar)
Check if the element that you want to use exists, if not, create it
var i = 0;
var j = 0;
var arr = [];
for( i = 0; i < 8; i++) {
for( j = 0; j < 8; j++) {
arr[i] = arr[i] || []; // Create array if needed
arr[i][j] = 'value';
}
}
here is the code for making a 2d array to be used as a board for conways game of life in node.js. i am having a problem with displaying the board. the output looks like this.
['-','-','-']
['-','-','-']
['-','-','-']
however i want it to look like this
---
---
---
this is the code right now. Does anyone have any suggestions?
var createBoard = (width, height) => {
board = [];
row = [];
for (var i = 0; i < width; i++) {
for (var j = 0; j < height; j++) {
row.push("-");
}
board.push(row);
row =[];
}
return (board);
}
var displayBoard = (board) =>{
for (var i = 0; i < board.length; i++) {
console.log(board[i]);
}
}
gameBoard = createBoard(3,3);
displayBoard(gameBoard);
You need to join the elements of the array to form a string.
var createBoard = (width, height) => {
board = [];
row = [];
for (var i = 0; i < width; i++) {
for (var j = 0; j < height; j++) {
row.push("-");
}
board.push(row);
row = [];
}
return (board);
}
var displayBoard = (board) => {
for (var i = 0; i < board.length; i++) {
console.log(board[i].join(""));
}
}
gameBoard = createBoard(3, 3);
displayBoard(gameBoard);
To fix your issue you should iterate over the array and add it to a string, like this:
var displayBoard = (board) =>{
var buffer = '';
for (var i = 0; i < board.length; i++) {
for (var x = 0; x < board[i].length; x++) {
buffer += board[i][x];
}
buffer += '\n';
}
console.log(buffer);
}
This should print it like this:
---
---
---
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 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/
I'm reading Data Structures and Algorithms with Javascript by O'reily and it states the following:
Shallow copy (two arrays point to the same location in memory):
var nums = [];
for (var i = 0; i < 100; ++i) {
nums[i] = i+1;
}
var samenums = nums;
nums[0] = 400;
print(samenums[0]); // displays 400
Deep copy:
function copy(arr1, arr2) {
for (var i = 0; i < arr1.length; ++i) {
arr2[i] = arr1[i];
}
}
Now the following code fragment produces the expected result:
var nums = [];
for (var i = 0; i < 100; ++i) {
nums[i] = i+1;
}
var samenums = [];
copy(nums, samenums);
nums[0] = 400;
print(samenums[0]); // displays 1
Why is a function required in order to create deep copies?
As stated in the comments, the function is purely for aesthetics and reusability, and is not strictly necessary.
You could refactor your example:
function copy(arr1, arr2) {
for (var i = 0; i < arr1.length; ++i) {
arr2[i] = arr1[i];
}
}
var nums = [];
for (var i = 0; i < 100; ++i) {
nums[i] = i+1;
}
var samenums = [];
copy(nums, samenums);
nums[0] = 400;
print(samenums[0]); // displays 1
into this equivalent function-less example:
var nums = [];
for (var i = 0; i < 100; ++i) {
nums[i] = i+1;
}
var samenums = [];
for (var i = 0; i < nums.length; ++i) {
samenums[i] = nums[i];
}
nums[0] = 400;
print(samenums[0]); // displays 1