Loop through array of images in javascript - javascript

I'm trying to loop through an array of images but can't seem to get past image 2.
The array should also loop back to 1 when the last image has passed...
var WorkArray = new Array('work/01.png', 'work/02.png', 'work/03.png', 'work/04.png');
var nelements = WorkArray.length;
preload_image_object = new Image();
var i = 0;
for(i=0; i<=nelements; i++) {
preload_image_object.src = WorkArray[i];
}
function cC() {
var nelements = WorkArray.length;
var i = 0;
for(i=0; i<=nelements; i++) {
nelements = WorkArray[i];
}
document.getElementById("work").style.backgroundImage="url('"+WorkArray[i]+"')";
}

You can save the current file and use modulo to run in cyclic manner.
It will look something like that:
var WorkArray = new Array('work/01.png', 'work/02.png', 'work/03.png', 'work/04.png');
var currentImage = 0
function nextImage(){
currentImage = (currentImage + 1) % WorkArray.length;
document.getElementById("work").style.backgroundImage="url('"+WorkArray[currentImage]+"')";
}

You are overwriting nelements with the current element of the loop:
nelements = WorkArray[i];

The following should fix your loops:
var WorkArray = new Array('work/01.png', 'work/02.png', 'work/03.png', 'work/04.png');
var preload_image_object = new Image();
/* Lets get rid of `nelements`, as its just confusing. Get the length here.
* If, for performace reasons you want to use elements, the best way is to reverse
* aka for(var i = WorkArray.length-1; i >= 0 ; i--)
* Also, its simpler to declare the var in your for-loop itself instead of outside of it.
*/
for(var i = 0; i <= WorkArray.length; i++){
preload_image_object.src = WorkArray[i];
}
Also, again for simplifications sake, your application of the background-image could be done inside your for loop as well, and can be made to look cleaner with some spaces and omitting the ' inside your url():
document.getElementById("work").style.backgroundImage = "url(" + WorkArray[i] + ")";

Related

2 random images but not the same one

I have this function that shows two random images picked from a folder. Is there any chance I can modify the code so that I won't have the same image twice as result?
Thanks in advance.
var theImages = new Array()
theImages[0] = 'img/dyptichs/f-1.jpg'
theImages[1] = 'img/dyptichs/f-2.jpg'
theImages[2] = 'img/dyptichs/f-3.jpg'
theImages[3] = 'img/dyptichs/f-4.jpg'
theImages[4] = 'img/dyptichs/f-5.jpg'
var j = 0
var p = theImages.length;
var preBuffer = new Array()
for (i = 0; i < p; i++){
preBuffer[i] = new Image()
preBuffer[i].src = theImages[i]
}
var WI1 = Math.round(Math.random()*(p-1));
var WI2 = Math.round(Math.random()*(p-2));
function showImage1(){
document.write('<img src="'+theImages[WI1]+'">');
}
function showImage2(){
document.write('<img src="'+theImages[WI2]+'">');
}
You can do something like this:
var WI1 = Math.round(Math.random()*(p-1));
var WI2 = Math.round(Math.random()*(p-1));
while (WI2 === WI1) {
WI2 = Math.round(Math.random()*(p-1));
}
We keep generating a new number until it's different from WI1, ensuring it is unique.
The way I'd personally handle that is to randomise the array and then just grab the first 2 entries. That way you still pick 2 at random, but you guarantee not to get the same 2.
var theImages = new Array()
theImages[0] = 'img/dyptichs/f-1.jpg'
theImages[1] = 'img/dyptichs/f-2.jpg'
theImages[2] = 'img/dyptichs/f-3.jpg'
theImages[3] = 'img/dyptichs/f-4.jpg'
theImages[4] = 'img/dyptichs/f-5.jpg'
var randomImages = theImages
.concat()
.sort(function () {
return Math.random() > 0.5
? 1
: -1;
})
.slice(0, 2);
function showImage1() {
document.write('<img src="' + randomImages[0] + '">');
}
function showImage2() {
document.write('<img src="' + randomImages[1] + '">');
}
Edit: including the original array for a complete solution
var WI1 = Math.floor(Math.random()*p);
var WI2 = Math.floor(Math.random()*(p-1));
if (WI2 >= WI1) {
WI2 += 1;
}
Use floor instead of round and subtract 1, because with round you get twice less chance to get first or last element.
The if trick is slightly better than a loop in this case, though the loop is easier to apply to a more complex case.

New to JavaScript and think I need a loop for this.....?

I've got a 180 character string of numbers which needed to be broken down into 6 groups, separated into 2 character figures and then sorted into ascending order.
I've done this, but it looks dirty and I'm pretty sure with my gradual improvement of understanding of JavaScript, that a neat little loop would save me a huge amount of repetition.
<script type="text/javascript">
var ticketString = "011722475204365360702637497481233455758302154058881928446789061241507324334876840738576186051132437816395663800818206590104559628214294664710935667287132130687703253151692742547985".match(/.{1,2}/g);
var groupa = ticketString.slice (0,15);
groupa.sort();
var groupb = ticketString.slice (15,30);
groupb.sort();
var groupc = ticketString.slice (30,45);
groupc.sort();
var groupd = ticketString.slice(45,60);
groupd.sort();
var groupe = ticketString.slice(60,75);
groupe.sort();
var groupf = ticketString.slice(75,90);
groupf.sort();
function displayArray () {
document.getElementById('ticketOne').innerHTML = groupa;
document.getElementById('ticketTwo').innerHTML = groupb;
document.getElementById('ticketThree').innerHTML = groupc;
document.getElementById('ticketFour').innerHTML = groupd;
document.getElementById('ticketFive').innerHTML = groupe;
document.getElementById('ticketSix').innerHTML = groupf;
}
The outputs are placed into paragraphs for now, but I know this could be done easier than the way I have it. The function displayArray loads off the body tag.
If you could rename your elements from ticketOne, ticketTwo etc to ticket1, ticket2 etc:
<script type="text/javascript">
var ticketString = "011722475204365360702637497481233455758302154058881928446789061241507324334876840738576186051132437816395663800818206590104559628214294664710935667287132130687703253151692742547985".match(/.{1,2}/g);
for (var i=0; i<ticketString.length/15; i++) {
var group = ticketString.slice(i*15, i*15+15);
group.sort();
document.getElementById('ticket'+(i+1)).innerHTML = group;
}
</script>
So here is what I think is the best solution:
var ticketString = "011722475204365360702637497481233455758302154058881928446789061241507324334876840738576186051132437816395663800818206590104559628214294664710935667287132130687703253151692742547985".match(/.{1,2}/g);
var group = [];
for (var i = 0; i < 180 / 15 / 2; i++) {
group[i] = ticketString.slice(i * 15, (i + 1) * 15);
group[i].sort();
document.getElementById('ticket[' + i + ']').innerHTML = group[i];
}
What I'm doing here is that I created a local array called group, which is in turn easier to handle within a loop than using a name like "group1" or "ticketFirst".
After that I practically did the same you did, but since I used the for loop I was able to short it down significantly.
The reason why I used i < 180 / 15 / 2 is because you're pairing them in character packs of 2. for (var i = 0; i < 180 / 15 / 2; i++) You ofcourse have to have an HTML like this:
<body>
<p id="ticket[0]"></p>
<p id="ticket[1]"></p>
<p id="ticket[2]"></p>
<p id="ticket[3]"></p>
<p id="ticket[4]"></p>
<p id="ticket[5]"></p>
</body>
You can reduce it to:
var groupArray = [];
for(var i=0;i<100;i+=15){
groupArray.push(ticketString.slice (i,15+i));
groupArray[groupArray.length-1].sort();
}
You could do something like this, if you changed your 'ticket' id's to a generic 'ticket' class;
var ticketString = "011722475204365360702637497481233455758302154058881928446789061241507324334876840738576186051132437816395663800818206590104559628214294664710935667287132130687703253151692742547985".match(/.{1,2}/g);
var tickElem = document.querySelectorAll('.ticket');
var strPoint = 0;
for(var i in tickElem)
{
var grp = ticketString.slice(strPoint, (strPoint += 15));
grp.sort();
tickElem[i].innerText = grp.join('');
}
How about this compact version:
var start = 0;
['ticketOne', 'ticketTwo', 'ticketThree', 'ticketFour', 'ticketFive', 'ticketSix']
.forEach(function (id) {
document.getElementById(id).innerHTML = ticketString.slice(start, start += 15).sort();
});
<script>
var ticketString ="011722475204365360702637497481233455758302154058881928446789061241507324334876840738576186051132437816395663800818206590104559628214294664710935667287132130687703253151692742547985".match(/.{1,2}/g);
function loadTickets () {
var ticket = [];
for (var i = 0; i < ticketString.length / 15; i++) {
ticket[i] = ticketString.slice(i * 15, (i + 1) * 15).sort();
var tableCre = document.createElement("TABLE");
tableCre.setAttribute("id","ticketTable" + i)
document.body.appendChild(tableCre);
document.getElementById('ticketTable' + i).innerHTML = ticket[i];
}
console.log(ticketString);
console.log(ticket);
};
</script>
Got it fixed, #Quikers - given you the thumbs up; as this was the thinking I had - brought the .sort() function into the ticket[i] variable to trim it a little and based on the number of arrays, I have dynamically created 6 tables that hold the strings inside them. I have to develop the tables and set them up, but I am pretty much there now. Thanks for all your help.

Syntax to build object properties in loop - javascript

I would like to loop through a list of objects and display one property on a graph on the page but I can't seem to get the right syntax to get this data in a loop.
Without the loop this gives an idea of what I want to do:
document.getElementById("v1").innerHTML = zone1.sensor;
document.getElementById("v2").innerHTML = zone2.sensor;
document.getElementById("v3").innerHTML = zone3.sensor;
I can't figure out how to loop through the objects, something like this:
for(i = 1; i < 7; i++) {
document.getElementById("v" + i).innerHTML = ("zone" + i + ".sensor");
}
While that can be done with eval() or new Function (), that's just plain wrong. Put your values in an array and access them by index. If you absolutely have to use independent variables, do:
var arr = [zone1, zone2, zone3];
and then use
arr[i].sensor
I would go this way to avoid the use of eval:
var zone1 = new Object;
var zone2 = new Object;
var zone3 = new Object;
zone1.sensor = "sensor1";
zone2.sensor = "sensor2";
zone3.sensor = "sensor3";
var zones = [zone1, zone2, zone3];
for( var i = 1; i < 4; i++) {
document.getElementById("v" + i).innerHTML = zones[i - 1]["sensor"];
}
<div id="v1"></div>
<div id="v2"></div>
<div id="v3"></div>
Hope it helps!

Javascript: using a for statement as a variable

I'm fairly new to javascript and something I've been playing with lately is the 'for' statement. I'm questioning one thing, though. I've learned how to make a 'for' statement do things as if it was an output, like this:
for (i = 0; i < 3; i++) {
console.log(i);
}
But what if you want to set a variable for the whole output of the 'for' statement?
var destinationArray = ["town", "areas", "bosses"];
var destinationArraySet = 1;
var i;
for ( i = 0; i < destinationArraySet; i++) {
console.log(destinationArray[i]);
} /*the whole thing should be equal to var destination */
var userDestinationPrompt = ("Where would you like to go? Available places: " +
/* var destination */
+
".").toUpperCase();
To give some more context: I'm making a game that allows further destinations when the destination before is cleared. Once that's achieved, I set destinationArraySet to a higher value, which means that more places would be logged and put after 'Available places'.
Help would be very appreciated! If there's something not clear enough let me know.
The for statement is not an expression, so it doesn't have a return value. Use a variable to collect values in the loop:
var destination = '';
for (var i = 0; i < destinationArraySet; i++) {
destination += destinationArray[i] + ' ';
}
Of course, if you only want to concatenate the values in part of an array, you can use the slice method to get part of it, then the join method:
var destination = destinationArray.slice(0, destinationArraySet).join(' ');
var destination = '';
var destinationArray = ["town", "areas", "bosses"];
var destinationArraySet = 1;
for (var i = 0; i < destinationArraySet; i++) {
destination += destinationArray[i] + '\n';
}
console.log(destination);
Try this -
var destinationArray = ["town", "areas", "bosses"];
var destinationArraySet = 1;
var i;
var availablePlaces = '';
var separator = '';
for ( i = 0; i < destinationArraySet; i++) {
availablePlaces += separator + destinationArray[i];
separator = ', ';
}
var userDestinationPrompt = ("Where would you like to go? Available places: " +
availablePlaces + ".").toUpperCase();
The for statement doesn't have an "output", it's not a function. Thinking for as a function will give you troubles later on. for is simply a statement that continuously execute the block of code inside. It does not "output", or in other words, return any value.
Do this instead:
var destinationArray = ["town", "areas", "bosses"], destinationArraySet = 1;
var userDestinationPrompt = ("Where would you like to go? Available places: " +
destinationArray.slice(0, destinationArraySet).join("\n")
+ ".").toUpperCase();
prompt(userDestinationPrompt);
Demo: http://jsfiddle.net/7c2b9q7m/1/
destinationArray.slice(0, destinationArraySet): Cuts the array to the specified length.
.join("\n"): Join the newly created array by \ns (newline) to micic the default console.log behavior.

Javascript variable stays undefined

I have a problem with this script, something is going wrong.
Rnumer stays undefined.This script should return and write all uneven digits from the random number list. Can someone tell me what I do wrong. Thanks in advance
var Rnumber = new Array();
for (i = 0; i<= 100;i++)
{
Rnumber[i] = Math.ceil(Math.random()*101);
// document.write(Rnumber[i] + "<br/>");
}
function unevenAndDivisible(Rnumber)
{
var remainder = new Array();
for (i = 0; i<= 100; i++)
{
remainder = parseInt(Rnumber[i])%2;
}
return remainder;
}
document.write(unevenAndDivisible());
Changed to
var Rnumber = new Array();
for (i = 0; i<= 100;i++)
{
Rnumber[i] = Math.ceil(Math.random()*101);
// document.write(Rnumber[i] + "<br/>");
}
function unevenAndDivisible(Rnumber)
{
var remainder = new Array();
for (i = 0; i<= 100; i++)
{
remainder[i] = Rnumber[i]%2;
}
return remainder;
}
document.write(unevenAndDivisible(Rnumber));
but now i get the result :
0,1,0,0,1,0,0,0,1,1,0,0,1,0,1,1,1....
I simply want maybe I asked it wrong the first time, to write al uneven numbers from the random list of Rnumbers
Then I need to divide that through 7 and return that.
EDIT
Allmost all problems are clear , thanks everyone for that.
Their is still one question left:
In this code below it only take the first uneven value from remainder and I want that it takes all values that are uneven to the next if statement to check %7.
Maybe you see the problem better if you run it for youreself
var Rnumber = new Array();
for (i = 0; i<= 100;i++)
{
Rnumber[i] = Math.ceil(Math.random()*101);
}
function unevenAndDivisible()
{
var remainder = [];
var answer = [];
for (i = 0; i<= 100; i++)
{
if (Rnumber[i]%2 !== 0)
{
remainder.push(Rnumber[i]);
for (c = 0; c <= remainder.length;c++)
{
if (remainder[c]%7 == 0)
{
answer.push(remainder[c]);
}
}
}
}
return answer;
}
answer = unevenAndDivisible();
document.write(answer);
Problem solved , Thanks everyone
You don't need to pass Rnumber to the function, as it's already available in scope:
function unevenAndDivisible()
{
var remainder = [];
for (i = 0; i<= 100; i++)
{
if (Rnumber[i]%2 !== 0) {
remainder.push(Rnumber[i]);
}
}
return remainder;
}
remainder = unevenAndDivisible();
console.log(remainder);
JS Fiddle demo.
Edited in response to question from OP (in comments to question, above):
...can someone explain what this mean: var remainder = [];
Sure, it's array-literal notation, which is equal to: var remainder = new Array();, it's just a little more concise, and I prefer to save myself the typing. I get the impression, from JS Lint, whenever I use var x = new Array(); therein that the above version is generally preferred (since it complains otherwise), but I don't know why.
Either pass Rnumber to the function unevenAndDivisible or omit it from the argument list. Since it is an argument, it has more local scope than the initial declaration of Rnumber.
Your problem is the line
function unevenAndDivisible(Rnumber)
You are passing in Rnumber in as an argument, but when you call unevenAndDivisible()
you are not passing it it.
Consequently for the body of the function Rnumber is undefined (cause you passed nothing in)
The following snippet is equivalent to what you wrote nad might explain better
function unevenAndDivisible(xyz)
{
var remainder = new Array();
for (i = 0; i<= 100; i++)
{
remainder = parseInt(xyz[i])%2;
}
return remainder;
}
then called as
unevenAndDivisible(undefined)
to fix it remove the argument from the call definition
i.e. define it as
function unevenAndDivisible()
1 - you is not defining the Rnumber value that's function argument.
2 - in loop, you're defining remainder to divised value of ranumber and is not saving in array; try:
change:
remainder = parseInt(Rnumber[i])%2;
to
remainder[i] = parseInt(Rnumber[i])%2;
var array = [],
i = 100;
while (i--) {
var random = Math.random()*i|0;
if(random % 2)
array.unshift(random);
}
alert(array);

Categories

Resources