Javascript - loop through the same array more than once - javascript

How do I get the below for loop statement to go through my array more than once?
var clients = new Array("client1", "client2", "client3", "client4", "client5");
var indexCounter;
var holmesminutes = 0;
for (indexCounter = 0; indexCounter < clients.length; indexCounter++) {
holmesminutes = holmesminutes + 15;
document.write(clients[indexCounter] + " testroom " + holmesminutes +"<br>");
}

Put another loop around the loop.
for (var repeatCounter = 0; repeatCounter < 5; repeatCounter++) {
for (indexCounter = 0; indexCounter < clients.length; indexCounter++) {
holmesminutes = holmesminutes + 15;
document.write(clients[indexCounter] + " testroom " + holmesminutes +"<br>");
}
}
To stop all the loops when holmesminutes reaches 315:
for (var repeatCounter = 0; repeatCounter < 5 && holmesminutes < 315; repeatCounter++) {
for (indexCounter = 0; indexCounter < clients.length && holmesminutes < 315; indexCounter++) {
holmesminutes = holmesminutes + 15;
document.write(clients[indexCounter] + " testroom " + holmesminutes +"<br>");
}
}
As you see, you can put any condition you want in the test clause of for, it doesn't have to refer only to the iteration variable.

Maybe try a while loop:
var clients = new Array("client1","client2","client3","client4","client5");
var indexCounter;
var holmesminutes =0;
_i= 0;
while (_i < 2) {
for(indexCounter = 0; indexCounter<clients.length;indexCounter++)
{
holmesminutes = holmesminutes + 15;
document.write(clients[indexCounter] + " testroom " + holmesminutes + "<br>");
_i++;
}
}

Related

Displaying times table using javascript

As I am new to JavaScript, I am a bit confused of using the for loops in JavaScript. I have tried the times table using the below JavaScript code, but I was unsuccessful in creating the times table for 1 to 9, as displayed in the image.
var display = ""; // The table output HTML
for (i = 1; i <= 9; i++) {
var multiplier = 1;
var result = i * 1;
display += multiplier + " * " + i + " = " + result + "\xa0\xa0\xa0\xa0\xa0\xa0\xa0 " ;
}
document.getElementById("outputDiv").innerHTML = display;
I tried using nested for loops, but it left me with an error
This is where I have done with a single for loop
https://codepen.io/vbudithi/pen/LgEPwx
I tried to get the output in the below form
THANKS IN ADVANCE
Use nested loop with break line. "< br >"
Working example: https://codepen.io/anon/pen/yRyLje
var display = "";
for( i = 1; i < 10; i++){
for (j = i; j < 10; j++) {
display += i + " * " + j + " = " + j * i+ "\xa0\xa0\xa0\xa0\xa0" ;
}
display +="<br>";
}
document.getElementById("outputDiv").innerHTML = display;
just like NicolasB said, wrapping the loop in another loop
var display = ""; // The table output HTML
for(j = 1; j <= 9; j++) {
for (i = j; i <= 9; i++) {
var result = i * j;
display += j + " * " + i + " = " + result + "\xa0\xa0\xa0\xa0\xa0\xa0\xa0 " ;
}
display += "<br>";
}
document.getElementById("outputDiv").innerHTML = display;

How do I assign numbers 10 through 16 a letter in this hex/binary table?

var count = -1;
var countLetter = "";
for (outer = 0; outer < 2; outer++) {
for (inner = 0; inner < 2; inner++) {
for (third = 0; third < 2; third++) {
for (fourth = 0; fourth < 2; fourth++) {
count++;
countLetter = count;
document.write(countLetter + "|" + "" + outer + "" + inner + "" + third + "" + fourth + ".</br>");
}
}
}
}
I attempted to add an if(count)=10{counterLetter="A"} and so on but this didn't work, either broke the code or ended up doing something wacky. Any help appreciated!
According to Number.prototype.toString() you may write:
countLetter = count.toString(16).toUpperCase();
The snippet:
var count = -1;
var countLetter = "";
for (outer = 0; outer < 2; outer++) {
for (inner = 0; inner < 2; inner++) {
for (third = 0; third < 2; third++) {
for (fourth = 0; fourth < 2; fourth++) {
count++;
countLetter = count.toString(16).toUpperCase();
document.write(countLetter + "|" + "" + outer + "" + inner + "" + third + "" + fourth + ".</br>");
}
}
}
}
A shorter version:
for (i = 0; i < 16; i++) {
document.write(i.toString(16).toUpperCase() + "|" + ("000" + i.toString(2)).slice(-4) + ".</br>");
}

array undefined in JavaScript

I've a array which is the following;
var imgArray = (function() {
var kleuren = ["harten", "klaveren", "koeken", "schoppen"];
var result = [];
for(var k = 0; k != kleuren.length; k++) {
for(var n = 1; n <= 13; ++n) {
result.push("images/" + kleuren[k] + "/" + kleuren[k] + n.toString() + ".png");
}
}
})();
And this is where I call my function/Array:
if(counter <= 5) {
var arrayIndex = computeIndex(type, face);
$('#cardplace' + counter).css("background-image", "url('" + imgArray[arrayIndex] + "')");
++counter;
} else {
alert("Je hebt te veel kaarten genomen...");
document.reload();
}
But my Nightly give the Error that imgArray is undefined,
where did i go wrong?
You need to
return result;
at the end of your function.

Change obj.innerHTML in Javascript? Game of Life

I have implemented the Game of Life in Javascript. I am thinking about making a combobox which a listof colors to choose from. From there I want to render the obj.innerHTML img source of my grid cells in the game. What would be the best way to go about this?
Here is my code so far for the game:
<br>
<canvas id="canvas" width="100%" height="80%"></canvas>
<button onClick="generateLevel()">Create New Board</button>
<button onClick="step()">Step</button>
<button onClick="multiStep()">Multistep</button>
<script type="text/javascript">
var level;
var lastLevelDrawn;
var lvlWidth = 0;
var lvlHeight = 0;
function step()
{
var tempLevel = new Array(lvlHeight);
for (var y = 0; y < lvlHeight; y++)
{
tempLevel[y] = new Array(lvlWidth);
for (var x = 0; x < lvlWidth; x++)
{
var liveNeighborCount = 0;
var status = level[y][x];
for (var k = y-1; k < y+2; k++)
{
for (var j = x-1; j < x+2; j++)
{
if (k == y && j == x)
{
}
else if (k >= 0 && k < lvlHeight && j >= 0 && j < lvlWidth)
{
if (level[k][j] == "1")
{
liveNeighborCount++;
}
}
}
}
if (level[y][x] == "1")
{
if (liveNeighborCount != 2 && liveNeighborCount != 3)
{
status = "0";
}
}
if (level[y][x] == "0")
{
if (liveNeighborCount == 3)
{
status = "1";
}
}
tempLevel[y][x] = status;
}
}
level = tempLevel;
render();
}
function multiStep()
{
var steps = prompt("How many steps do you want to step?", "10");
for (var x = 0; x < steps; x++)
step();
}
function generateLevel()
{
var width = prompt("How many cells wide?", "10");
var height = prompt("How many cells high?", "10");
lvlWidth = width;
lvlHeight = height;
var output = "";
if (width != null && height != null)
{
level = new Array(lvlHeight);
lastLevelDrawn = new Array(lvlHeight);
for (var y = 0; y < height; y++)
{
level[y] = new Array(lvlWidth);
lastLevelDrawn[y] = new Array(lvlWidth);
for (var x = 0; x < width; x++)
{
level[y][x] = Math.floor((Math.random()*2));
lastLevelDrawn[y][x] = -1;
output += " " + level[y][x];
}
output += "<br>";
}
}
//document.getElementById("demo").innerHTML=output;
setupRender();
}
function changeTile(tile)
{
var x = tile % lvlWidth;
var y = parseInt(tile/lvlWidth);
//document.getElementById("demo").innerHTML=x + ":" + y;
if (level[y][x] == "1")
level[y][x] = "0";
else
level[y][x] = "1";
render();
}
function render()
{
var widPer = ((1/lvlWidth)*90);
var heiPer = ((1/lvlHeight)*70);
for (var y = 0; y < lvlHeight; y++)
{
for (var z = 0; z < lvlWidth; z++)
{
var send = y*lvlWidth + z;
if (lastLevelDrawn[y][z] != level[y][z])
{
lastLevelDrawn[y][z] = level[y][z];
var obj = document.getElementById(send);
if (level[y][z] == "1")
obj.innerHTML = "<img src='white.jpg' width='" + widPer + "%' height='" + heiPer + "%' onclick='changeTile(" + send + ")'/>";
else
obj.innerHTML = "<img src='black.jpg' width='" + widPer + "%' height='" + heiPer + "%' onclick='changeTile(" + send + ")'/>";
}
}
}
}
function setupRender()
{
var x = "";
var widPer = ((1/lvlWidth)*90);
var heiPer = ((1/lvlHeight)*70);
//x += "<table border='1' col width='((1/lvlWidth)*100)%' col height='((1/lvlHeight)*80)%'>";
for (var y = 0; y < lvlHeight; y++)
{
//x += "<tr>";
for (var z = 0; z < lvlWidth; z++)
{
lastLevelDrawn[y][z] = level[y][z];
//x += level[y][z];
var send = y*lvlWidth + z;
x += "<n id='" + send + "'>";
if (level[y][z] == "1")
x += "<img src='white.jpg' width='" + widPer + "%' height='" + heiPer + "%' onclick='changeTile(" + send + ")'/>";
else
x += "<img src='black.jpg' width='" + widPer + "%' height='" + heiPer + "%' onclick='changeTile(" + send + ")'/>";
x += "</n>";
}
x += "<br>";
//x += "</tr>";
}
//x += "</table>";
document.getElementById("demo").innerHTML=x;
}
</script>

Javascript Hanging UI on IE6/7

Could anyone suggest performance improvements for the function I've written (below, javascript with bits of jquery)? Or point out any glaring, basic flaws? Essentially I have a javascript Google map and a set of list based results too, and the function is fired by a checkbox click, which looks at the selection of checkboxes (each identifying a 'filter') and whittles the array data down accordingly, altering the DOM and updating the Google map markers according to that. There's a 'fake' loader image in there too at the mo that's just on a delay so that it animates before the UI hangs!
function updateFilters(currentCheck) {
if (currentCheck == undefined || (currentCheck != undefined && currentCheck.disabled == false)) {
var delay = 0;
if(document.getElementById('loader').style.display == 'none') {
$('#loader').css('display', 'block');
delay = 750;
}
$('#loader').delay(delay).hide(0, function(){
if (markers.length > 0) {
clearMarkers();
}
var filters = document.aspnetForm.filters;
var markerDataArray = [];
var filterCount = 0;
var currentfilters = '';
var infoWindow = new google.maps.InfoWindow({});
for (i = 0; i < filters.length; i++) {
var currentFilter = filters[i];
if (currentFilter.checked == true) {
var filtername;
if (currentFilter.parentNode.getElementsByTagName('a')[0].textContent != undefined) {
filtername = currentFilter.parentNode.getElementsByTagName('a')[0].textContent;
} else {
filtername = currentFilter.parentNode.getElementsByTagName('a')[0].innerText;
}
currentfilters += '<li>' + $.trim(filtername) +
$.trim(document.getElementById('remhide').innerHTML).replace('#"','#" onclick="toggleCheck(\'' + currentFilter.id + '\');return false;"');
var nextFilterArray = [];
filterCount++;
for (k = 0; k < filterinfo.length; k++) {
var filtertype = filterinfo[k][0];
if (filterinfo[k][0] == currentFilter.id) {
var sitearray = filterinfo[k][1];
for (m = 0; m < sitearray.length; m++) {
var thissite = sitearray[m].split(',');
if (filterCount > 1) {
nextFilterArray.push(thissite[2] + '|' + thissite[1]
+ '|' + thissite[0]);
} else {
markerDataArray.push(thissite[2] + '|' + thissite[1]
+ '|' + thissite[0]);
}
}
}
}
if (filterCount > 1) {
var itemsToRemove = [];
for (j = 0; j < markerDataArray.length; j++) {
var exists = false;
for (k = 0; k < nextFilterArray.length; k++) {
if (markerDataArray[j] == nextFilterArray[k]) {
exists = true;
}
}
if (exists == false) {
itemsToRemove.push(j);
}
}
var itemsRemoved = 0;
for (j = 0; j < itemsToRemove.length; j++) {
markerDataArray.splice(itemsToRemove[j]-itemsRemoved,1);
itemsRemoved++;
}
}
}
}
if (currentfilters != '') {
document.getElementById('appliedfilters').innerHTML = currentfilters;
document.getElementById('currentfilters').style.display = 'block';
} else {
document.getElementById('currentfilters').style.display = 'none';
}
if (filterCount < 1) {
for (j = 0; j < filterinfo.length; j++) {
var filtertype = filterinfo[j][0];
if (filterinfo[j][0] == 'allvalidsites') {
var sitearray = filterinfo[j][1];
for (m = 0; m < sitearray.length; m++) {
var thissite = sitearray[m].split(',');
markerDataArray.push(thissite[2] + '|' + thissite[1]
+ '|' + thissite[0]);
}
}
}
}
var infoWindow = new google.maps.InfoWindow({});
var resultHTML = '<div id="page1" class="page"><ul>';
var count = 0;
var page = 1;
var paging = '<li class="selected">1</li>';
for (i = 0; i < markerDataArray.length; i++) {
var markerInfArray = markerDataArray[i].split('|');
var url = '';
var name = '';
var placename = '';
var region = '';
var summaryimage = 'images/controls/placeholder.gif';
var summary = '';
var flag = 'images/controls/placeholderf.gif';
for (j = 0; j < tsiteinfo.length; j++) {
var thissite = tsiteinfo[j].split('|');
if (thissite[0] == markerInfArray[2]) {
name = thissite[1];
placename = thissite[2];
region = thissite[3];
if (thissite[4] != '') {
summaryimage = thissite[4];
}
summary = thissite[5];
if (thissite[6] != '') {
flag = thissite[6];
}
}
}
for (k = 0; k < sitemapperinfo.length; k++) {
var thissite = sitemapperinfo[k].split('|');
if (thissite[0] == markerInfArray[2]) {
url = thissite[1];
}
}
var markerLatLng = new google.maps.LatLng(markerInfArray[1].toString(), markerInfArray[0].toString());
var infoWindowContent = '<div class="infowindow">' + markerInfArray[2] + ': ';
var siteurl = approot + '/sites/' + url;
infoWindowContent += '<strong>' + name + '</strong>';
infoWindowContent += '<br /><br/><em>' + placename + ', ' + region + '</em></div>';
marker = new google.maps.Marker({
position: markerLatLng,
title: $("<div/>").html(name).text(),
shadow: shadow,
icon: image
});
addInfo(infoWindow, marker, infoWindowContent);
markers.push(marker);
count++;
if ((count > 20) && ((count % 20) == 1)) { // 20 per page
page++;
resultHTML += '</ul></div><div id="page' + page + '" class="page"><ul>';
paging += '<li>' + page + '</li>';
}
resultHTML += '<li><div class="namehead"><h2>' + name + ' <span>' + placename + ', ' + region + '</span></h2></div>' +
'<div class="codehead"><h2><img alt="' + region + '" src="' + approot +
'/' + flag + '" /> ' + markerInfArray[2] + '</h2></div>' +
'<div class="resultcontent"><img alt="' + name + '" src="' + approot +
'/' + summaryimage +'" />' + '<p>' + summary + '</p>' + document.getElementById('buttonhide').innerHTML.replace('#',siteurl) + '</div></li>';
}
$('#filteredmap .paging').each(function(){
$(this).html(paging);
});
document.getElementById('resultslist').innerHTML = resultHTML + '</ul></div>';
document.getElementById('count').innerHTML = count + ' ';
document.getElementById('page1').style.display = 'block';
for (t = 0; t < markers.length; t++) {
markers[t].setMap(filteredMap);
}
});
}
}
function clearMarkers() {
for (i = 0; i < markers.length; i++) {
markers[i].setMap(null);
markers[i] = null;
}
markers.length = 0;
}
However, I'm suffering from performance issues (UI hanging) specifically in IE6 and 7 when the number of results is high, but not in any other modern browsers, i.e. FF, Chrome, Safari etc. It is much worse when the Google map markers are being created and added (if I remove this portion it is still slugglish, but not to the same degree). Can you suggest where I'm going wrong with this?
Thanks in advance :) Please be gentle if you can, I don't do much javascript work and I'm pretty new to it and jquery!
This looks like a lot of work to do at the client no matter what.
Why don't you do this at the server instead, constructing all the HTML there, and just refresh the relevant sections with the results of an ajax query?

Categories

Resources