Javascript Array is Breaking my Loop - javascript

So I'm having some difficulty with this two dimensional array that I've created.
I've declared it like so:
var objects = new Array();
And then I run two loops, one inside the other, and in doing so, call values to the array, but it seems to break my entire loop (and thus the script) when it does run.
for(var i = 0; i <= 32; i++) {
dirtRows++;
document.getElementById("dirtTable").innerHTML+='<div class="dr" id="dirtRow-' + i + '"></div>';
alert(i);
for(var ii = 0; ii < 32; ii++) {
dirtBlocks++;
document.getElementById("dirtRow-" + i).innerHTML+='<div class="dirt" onclick="destroyIt(' + i + ',' + ii + ')" id="dirt-' + ii + '">' + ii + '</div>';
objects[i][ii] = 1;
}
}
What might I be doing wrong? It's definitely the Array that's breaking it.

You haven't created the inner arrays.
var objects = []; // Use an array literal, not new Array()
for (var i = 0; i <= 32; i++) {
objects[i] = []; // Create sub-array
dirtRows++;
document.getElementById("dirtTable").innerHTML+='<div class="dr" id="dirtRow-' + i + '"></div>';
alert(i);
for(var ii = 0; ii < 32; ii++) {
dirtBlocks++;
document.getElementById("dirtRow-" + i).innerHTML+='<div class="dirt" onclick="destroyIt(' + i + ',' + ii + ')" id="dirt-' + ii + '">' + ii + '</div>';
objects[i][ii] = 1;
}
}

You have to declare objects[i] to be an array:
objects[i] = new Array();
objects[i][ii] = 1;

Related

Javascript Fib series test case fails

I am trying to complete this assignment for the Javascript Fibonacci series. The logic works for input 5 and 6. But the test case for 8 fails.
function fibonacciSequence(input) {
//Type your code here.
var i = 0;
var fib = [];
fib[0] = 0;
fib[1] = 1;
var out ="0"+ "" +"1";
for (i = 2; i <=input; i++) {
fib[i] = fib[i-2] + fib[i-1];
out = out+ ""+ fib[i];
console.log("i is" + i + " out is" + out);
}
return out;
}
I cannot figure out what is going wrong..
It seems like things are just getting messed up with how you are adding the items to the string. Since there is no space between out + "" + fib[i], I think that would be messing with the formatting. Once i had spaces it seems to work fine, a double digit number wouldnt mess with a string like that.
function fibonacciSequence(input) {
var fib = [];
fib[0] = 0;
fib[1] = 1;
let out = ""
out+= ` ${0} `
out+= `${1}`
for (let i=2; i <=input; i++) {
fib[i] = fib[i-2] + fib[i-1];
out+= ` ${fib[i]}`
}
return out;
}
You are comparing the input (which it seems like this is maybe the number you want to stop at) to i which (plus or minus a bit) is the number of numbers in the list. You probably want to be comparing fib[i], or something like it to input to decide whether to terminate the loop.
Edit: If that's wrong and you do want input to be the number of numbers in the list, then you could just join fib at the end:
function fibonacciSequence(input) {
//Type your code here.
var i = 0;
var fib = [];
fib[0] = 0;
fib[1] = 1;
//var out ="0"+ "" +"1";
for (i = 2; i <=input; i++) {
fib[i] = fib[i-2] + fib[i-1];
//out = out+ ""+ fib[i];
//console.log("i is" + i + " out is" + out);
}
return fib.join(' ');
}
for(let j = 0; j < 9; j++)
console.log('input: ' + j + ' :: ', fibonacciSequence(j));
Unless ... I've got the wrong end of the stick and #Grant Herman's answer already does what you want?

Calling concatenated variables in Javascript

Is there a way to include variables in each iteration of a javascript loop? For example if I put this code into a loop
if (e1) {item_text += '{id:"' + id[1] + '",lvl:' + e1lvl + '},<wbr>'}
if (e2) {item_text += '{id:"' + id[2] + '",lvl:' + e2lvl + '},<wbr>'} // etc
and do something like
for (n = 0; n < id.length; n++) {
if (e/*concat var e w/var n?*/) {
item_text += '{id:"' + id[1] + '",lvl:' + e/*concat var e w/var n?*/lvl + '},<wbr>'
}
}
Is there a way to change the number in the var names (e1 -> e2 etc) each iteration or do i just have to keep it the long way and write everything out on its own line?
It would be possible, though highly not recommended, to use eval to come up with the variable name:
const e1lvl1 = 'foo';
const e2lvl1 = 'bar';
for (let i = 1; i < 3; i++) {
console.log(eval('e' + i + 'lvl1'));
}
But it would be better to fix your script's architecture so that this isn't necessary: put each e#lvl into an array, and then access the appropriate index of the array on each iteration:
const elvl = [
'foo',
'bar'
];
let item_text = '';
for (let i = 0; i < elvl.length; i++) {
item_text += 'lvl: ' + elvl[i] + '\n';
}
console.log(item_text);
Arrays/Objects exist in javascript for a reason! Simplify your code. There is no reason to have e1, e1l, e2... as variables. Add them to an object and access them by key, or add them to an array, and loop through them. There are many javascript functions as well that will allow you to ensure all elements match a certain condition.
function submit() {
var e = {};
var idx = 28;
for (var i = 0; i <= 24; i++) {
e[i] = {};
e[i].key = document.getElementById(`ench${i}`).checked
e[i].value = $.trim(form.elements[idx].value)
idx += 2;
}
// Check condition
if (Object.values(e).some(e => e.key)) {
//One of the checked items was true
}
}
I would agree that you should change your code to use arrays.
To answer your question though, since your e1 and e1lvl variables look to be global scope, you can access them like this
window["e1"]
window["e1lvl"]
Give this a try
for (n = 0; n < id.length; n++) {
if (window["e" + n]) {
item_text += '{id:"' + id[n] + '",lvl:' + window["e" + n + "lvl"] + '},<wbr>';
}
}

Trying to pass by value in Javascript multi-dim array

So, I'm building a web site that you can play othello on as a code sample. I've got a multidimensional array as the behind-the-scenes gameboard, and then iterate through every 'td' in a table to match the value of the corresponding array member. The problem i'm encountering is that iterating through the table. and using the iterators as essentially coordinates to my array doesn't work. As the iterator increases in value, so too does the coordinates in each of my 'td's. I'm stumped, and running on fumes. Any help would be appreciated.
function gridArray() {
// creates game board's array.
for (var i = 0; i < gameArray.length; i++) {
gameArray[i] = new Array(8);
}
for (var row = 0; row < gameArray.length; row++) {
for (var col = 0; col < gameArray[row].length; col++) {
gameArray[row][col] = "green";
}
}
}
function drawGrid(){
// writes table to HTML document
var htmlString = "<table id='othelloGrid'><tr>";
for (var i = 0; i < 8; i++) {
htmlString += "<th>" + i + "</th>";
}
htmlString += "</tr>";
for (var j = 0; j < 8; j++) {
htmlString += "<tr>";
xPos = j;
for (var x = 0; x < 8; x++) {
yPos = x;
// HERE!!! I now realize javascript passes by reference, so as this loop iterates,
// every single 'td' is getting 'onclick = 'changeClass(7, 7)''.
// for my game grid to work, I need each td to have a unique xPos, yPos to
// connect back to gameArray.
htmlString += "<td onclick = 'changeClass(xPos, yPos)'></td>";
}
htmlString += "</tr>";
}
htmlString += "</table>";
return htmlString;
}
Variables are not expanded inside strings. So all your TDs have the literal attribute onclick='changeClass(xPos, yPos)' in them, not the values of these variables from the loop. So when you actually click on them, they all use the most recent values of those variables.
You need to use string concatenation to get the values. And there's no need for the global variables xPos and yPos, you can use the local j and x variables.
htmlString += "<td onclick = 'changeClass(" + j + ", " + x + ")'></td>";

Why all my loops don`t work?

http://jsfiddle.net/VaAlina/oupmd0hf/
Commented code don`t work.
Area next to bomb is green. Yellow - bombs. Blue - emptiness .
I want to replace this kind of code->
var dangerItem1 = "#" + danger1;//Replace thise code to commented
var dangerItem2 = "#" + danger2;
var dangerItem3 = "#" + danger3;
var dangerItem4 = "#" + danger4;
With this->
/*
for(var j = 0; j < 4; j++){
var dangerItem+j = "#" + danger+j;
}
*/
Where is the mistake?
You can't dynamically create a variable name.
What you could do though is store them in arrays or objects.
Objects can accept dynamic property names using [] notation.
var danger =['green','red','blue','pink'];
var dangerItem = [];
for(var j = 0; j < 4; j++){
dangerItem.push( "#" + danger[j]);
}
// returns ["#green", "#red", "#blue", "#pink"]
/* or */
var dangerItem = {};
for(var j = 0; j < 4; j++){
dangerItem[ danger[j] ] = "#" + danger[j];
}
// returns {"green":"#green","red":"#red","blue":"#blue","pink":"#pink"}

How to use join (in built method) in javascript?

In javascript loop i am generating a xml like this:
for (m = 0; m < t.length; m++) {
var arr1 = t[m].split("\t");
s = "'<row dc= '" + arr1[0] + "' al='" + arr1[1] + "' msg='" + arr1[2] + "' />'";
alert(s);
//s = s.join(' ');
}
Forgot about the t variable and all. by run this code i am getting the s value in the following format:
<row dc = "abc" al="56" msg="dkaj" />
In the second iteration it shows like this:
<row dc = "abwwc" al="56w" msg="dkajad" />
and so on till the m<t.length satisfy. What i want to join the list in each iteration. After joining all of them i should get in this way:
<row dc = "abc" al="56" msg="dkaj" /><row dc = "abwwc" al="56w" msg="dkajad" /> and so on..
I tried to do it with join written in comment section, but didn't work for me. What i am doing wrong?
The best way would be to define a string outside the loop an append to it;
var v = '';
for (m = 0; m < t.length; m++) {
var arr1 = t[m].split("\t");
s = "'<row dc= '" + arr1[0] + "' al='" + arr1[1] + "' msg='" + arr1[2] + "' />'";
alert(s);
v += s;
}
alert(v);
If you still want to use join(), make v an array and push() elements on to it (note that join() is an array method, not for string's)
var y = [];
for (m = 0; m < t.length; m++) {
var arr1 = t[m].split("\t");
s = "'<row dc= '" + arr1[0] + "' al='" + arr1[1] + "' msg='" + arr1[2] + "' />'";
alert(s);
y.push(s);
}
alert(y.join(''));
You'll be pleased to see I've tried to adhere to your variable naming conventions in my examples (i.e. meaningless characters).

Categories

Resources