Get a sequence of images into an array - javascript

I was wondering if it's possible to get a sequence of pictures into an array. I'd like to use plain JavaScript, because I have zero experience in PHP or any other language to achieve this.
So I created a map called "images", which contains 50 images. The first one is called: "1", the second one is called: "2" and so on. They all are the same type (.jpg).
I can do this manually like:
var pictures = new Array();
pictures[0] = "images/1.jpg";
pictures[1] = "images/2.jpg";
//and so on
But only a mad man would do this. also when I upload a new picture to the "images" folder, I have to manually add the new image to the array, so I was thinking about a while loop which checks if each image in the folder is stored into the array.

You could try:
var pictures = new Array();
for(var x=1; x<51; x++ ) {
pictures[x-1] = "images/"+x+".jpg";
}

var numberOfImages = 50; // or whatever
var im, pictures = new Array();
for (var i = 0; i < numberOfImages ; i++) {
im = "images/" + i + ".jpg";
pictures.push(im);
}

var arr = [];
for (var i = 0, max = 50; i < max; i += 1) {
arr[i] = "images/" + i + ".jpg";
}
If you want a change number of images, try this:
function bar (numberOfImages) {
var arr = [];
for (var i = 0; i < numberOfImages; i += 1) {
arr[i] = "images/" + i + ".jpg";
}

Related

How to generate an array of Images using for loop in javascript?

I'm trying to write an array of images, but I have a lot of images so I'm trying to use "for loop" to generate it.
my current code is :
var images = [
"/images/image0000.png",
"/images/image0005.png",
"/images/image0010.png",
"/images/image0015.png",
"/images/image0020.png",
"/images/image0025.png",
"/images/image0030.png",
"/images/image0040.png",
"/images/image0045.png",
"/images/image0050.png"
];
I have more images to add. so I would like to know how to use for loop to generate this.
The last image is /images/image3360.png
Thank you!
I think you don't want to generate the actual images, but rather fill an array with filenames. The simplest way would be:
const MAX = 3360;
const PREFIX = "/images/image";
const EXT = ".png";
const arr = [];
for (let i = 0; i <= MAX; i += 5) {
arr.push(
PREFIX + ("0000" + i).slice(-4) + EXT
);
}
The slice thing comes from this answer.
const step = 5; // Steps
const imgNumber = 3360/step; // Image number
const images = []; // Array to hold images
for(i = 0; i<=imgNumber; i++) {
const currNum = i*step; // Calculate suffix
let str = "/images/image0000";
str = str.substring(0, str.length - currNum.toString().length); // Compile number
images.push(`${str}${currNum}.png`); // Store the image in the array
}
console.log(images);
You can do it like this:
let images = [];
for (let i = 0; i <= 3360; i += 5) {
let imageString = "";
let numberOfZeros = 4 - i.toString().length;
for (let j = 0; j < numberOfZeros; j++) {
imageString += "0";
}
images.push("/images/image" + imageString + i.toString() + ".png");
}
This essentially runs a for loop which increments by 5 each time, calculates the amount of leading zeros needed, then runs another for loop to add these leading zeros, and inserts a concatenation of this and the actual number inside the string which gets pushed to the array.

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.

How to format the element inside an array?

I have three arrays for example:
var name = ["wheel", "rectangle", "moon"];
var type = ["car", "shape", "sky"];
var all = [];
var temp = " ";
for (var i = 0; i < name.length; i++) {
temp = name[i] + " " + type[i];
all.push(temp);
}
for (var i = 0; i < name.length; i++) {
// I call here function to display all element of array `all`
}
The output is:
wheel car
rectangle shape
moon sky
But the format of output is not nice. I want to shift the element of array type before add them to array all, so I want the output to be like:
wheel car
rectangle shape
moon sky
My question is: how can I shift elements of the array to add them to another array and store them in a way that allows to me to display the elements like form above ?
But the form of output not nice
If you simply want to format the output in a better way, then try console.table
var name1 = [ "wheel","rectangle","moon" ];
var type = [ "car" , "shape", "sky"];
var all=[];
for (var i = 0; i< name1.length; i++)
{
all.push({ name : name1[i], type: type[i] });
}
console.table(all);
Try this fiddle to see the actual output since stack-snippet alters the behaviour of console api
You should calculate which is the longest string in the first array so to know in advance how many spaces you need to append to correctly pad the string
var n = ["wheel", "rectangle", "moon"];
var t = ["car", "shape", "sky"];
var all = [];
/* sorting the values of the first array by length desc,
* then get the length of the first element
*/
var padding = n.sort(function(a, b) {
return a.length <= b.length;
})[0].length + 1;
n.forEach(function(el, i) {
all.push(el + " ".repeat(padding - el.length) + t[i]);
});
Output
"rectangle car"
"wheel shape"
"moon sky"
codepen demo
First loop over the array and find the max length. Then loop again and add spaces.
<script >
var name=["wheel","rectangle","moon"];
var type=["car","shape","sky"];
var all=[];
var i=0;
var maxLength=0;
string temp=" ";
String.prototype.padLeft= function(len, c){
var r = '';
while(r.length < len) r += c;
return s+r;
}
for (i = 0; i< name.length; i++)
{
maxLength = Math.max(maxLength, name[i].length+type[i].length+1;
}
for (i = 0; i< name.length; i++)
{
temp=name[i]+type[i].padLeft(maxLength-name[i].length-type[i].length);
all.push(temp);
}
</script >
I would do as follows;
var id = ["wheel","rectangle","moon"],
type = ["car","shape","sky"];
id.longestStringLength = Math.max(...id.map(s => s.length));
type.longestStringLength = Math.max(...type.map(s => s.length));
id = id.map((s,_,a) => s + " ".repeat(a.longestStringLength-s.length));
type = type.map((s,_,a) => " ".repeat(a.longestStringLength-s.length) + s);
console.log(id,type);
Use \t instead of space while concatenating to make it aligned.
Why don't you just add tab '\t' and it will give you the desired output. Or you can append fixed number of spaces between the two array items.

Loop through array of images in 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] + ")";

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.

Categories

Resources