Output an Array using a for loop - javascript

I need to create an Array asking the user for 5 values to enter.
They must enter city names (strings) and I need to create that using a for loop.
Then I need to output that information using another for loop.
Here is what I have so far:
//Declare the variables
var cities= array(SIZE);
var SIZE = 5;
var index = 0;
var BR = "<br />";
// Create the for loop to prompt the user
for(index = 0; index < SIZE ; index++) {
cities= prompt("Please enter the cities!");
}
//Output the array information
for( /* ? */ ) {
document.write(cities[SIZE]+ " was the city you entered" + BR);
}
I don't know what to put between the for() to output that information. Is there a better way to do this?

The main problem is that you're not adding to the cities - you're replacing the array with a string, each time through the loop. You want to use push() instead.
And don't output cities[SIZE] - that will be past the end of the array. Loop through (just like on input) and output cities[index].
//Declare the variables
var SIZE = 5;
var cities = new Array(SIZE); // JS is case-sensitive
var index = 0;
var BR = "<br />";
//Create the for loop to prompt the user
for (index = 0; index < SIZE; index++) {
cities[index] = prompt("Please enter the cities!");
}
//Output the array information
for (index = 0; index < SIZE; index++) {
document.write(cities[index] + " was the city you entered" + BR);
}

Paul is right. In the first loop you directly set cities variable to the input entered by the user. Also you don't need to set the Array size. Best practice is to use brackets. Shortened version could be:
//Declare the variables
var size = 5,
cities = [];
//Create the for loop to prompt the user
for (var index = 0; index < size; index++) {
cities.push(prompt("Please enter the cities!"));
}
//Output the array information
for (var index in cities) {
document.write(cities[index] + " was the city you entered <br />");
}

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.

javascript for loop for json variables in localStorage only displays last item in wtform

I'm trying to populate a wtform textareafield with items from a json array stored in localStorage. There should be 1 value on each line like this:
value1
value2
value3
when I get the items with my for loop only the last item is displayed.
value3
Any assistance would be greatly appreciated.
function getValue() {
//sets requirements as a json array
var myinputs = $("[id^=reqInput]").map(function(){
return this.value;
}).get();
localStorage.setItem("reqs", JSON.stringify(myinputs));
console.log(myinputs);
// calls arrays and populates criteria form
for (var i = 0; i < myinputs.length; i++) {
var reqArray = myinputs[i];
console.log(reqArray);
document.getElementById("mission").value = reqArray;
};
};
From your code, the statement below will always replace the previous value with the new one on each loop:
document.getElementById("mission").value = reqArray;
If you want each value to be printed in separates line, you need to append the value on the #mission (not replacing it), and put <br /> in between.
Example:
// empty the element at first
document.getElementById("mission").innerHTML = ""
for (var i = 0; i < myinputs.length; i++) {
var reqArray = myinputs[i];
document.getElementById("mission").innerHTML += reqArray + "<br />";
};
I made the following adjustments based of feedback from Noval Agung Prayogo and it works perfectly!
function getValue() {
//sets requirements as a json array
var myinputs = $("[id^=reqInput]").map(function(){
return this.value;
}).get();
sessionStorage.setItem("reqs", JSON.stringify(myinputs));
console.log(myinputs);
document.getElementById("mission").value = ""
for (var i = 0; i < myinputs.length; i++) {
var reqArray = myinputs[i];
document.getElementById("mission").value += reqArray + '\n';
};
};

undefined parameter in js

I am receiving a type error stating that the array testA[i] is undefined whenever I add an input into the html page. I have the array set and i'm trying to add the value of currency to the array using the push method to add to the second part of the array i.e([0][currency])
function Test() {
var testA = [];
for (i = 0; i < 4; i++) {
this.currency = prompt("Please enter a 3-letter currency abbreviation", "");
testA[i].push(currency);
}
}
var index = new Test();
any help as to why the array is undefined would be appreciated.
Note: I have now tried both testA.push(currency) and testA[i] = this.currency, and I still get the same error as before.
Note: the final version should have it loop through 4 different questions asked and each time adding these into an array. At the end of the loop a new variant of the array should be made and the new set of data entered will be added to it. something like
for(i = 0; i < 4; i++) {
testA[i] = i;
for(j = 0; j < 4; j++) {
this.currency = prompt("Please enter a 3-letter currency abbreviation", "");
testA[i][j] = this.currency;
}
}
but at this point in time I'm just trying to get it to work.
You don't use the push method on a index. You use it on the array itself.
Replace this
testA[i].push(currency);
With this
testA.push(currency);
You need to perform push operation on the array directly.
testA.push(currency);
By executing testA[index] you will receive hold value. In JS it will always return undefined, if index is greater than array length.
Because your array is empty as the beginning, you are always receiving undefined.
You are mixing up two different implementation.
Either you use direct assignation.
var testA = new Array(4);
for (i = 0; i < 4; i += 1) {
this.currency = prompt('...', '');
testA[i] = this.currency;
}
Either you push new values into the array.
var testA = [];
for (i = 0; i < 4; i += 1) {
this.currency = prompt('...', '');
testA.push(this.currency);
}
You should use the second one, which is the most simple soluce.
testA[i] = this.currency OR testA.push(this.currency)
Use Modified function below
function Test() {
var testA = [];
for (i = 0; i < 4; i++) {
this.currency = prompt("Please enter a 3-letter currency abbreviation", "");
testA[i] = this.currency; // use this.currency here if you
}
console.log(testA);
}
var index = new Test();

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.

Iterating through Array of Objects to fill input fields

I am currently working on a workaround for Google Forms which will be able to store all inputs in cookies so a user can proceed the survey at a different time.
At the moment I am able to store all questions (a Question is a object that contains: id of the surrounding div, required, userinput in a cookie by using JSON.stringify(). I am also able to read and parse the cookie which gets me an array of all question objects.
Now I want to fill all fields or check all radio buttons which have a value.
My problem is, that the inner for loop does only 2 iterations but it should do 18. Do you have any idea what could be wrong?
function restoreInputs() {
// number of stored cookies
var countCookies = 27;
console.log(countCookies);
// iterate through all cookies
for (var i = 1; i < countCookies + 1; i++) {
var cookiename = "answer" + i;
// get content of cookie (is array of objects)
var answer = checkCookie(cookiename);
// iterate through content
for (var j = 0; j < answer.length; j++) {
// get value of object
var val = answer[j].value;
// get the input field (textarea or radio button)
var x = document.getElementById(answer[j].n).getElementsByTagName('input');
// if input is radio, then check the one at position stored in value of object
if (x[j].type === "radio") {
x[val].checked = true;
// if textarea set its value to the one stored in object value
} else {
x[j].value = val;
}
console.log("j: " + j);
}
}
console.log(i);
}
I found the solution. The problem was that I forgot a for loop, since var x = document.getElementById(answer[j].n).getElementsByTagName('input'); may return more than one element. So here is the solution:
function restoreInputs() {
// number of stored cookies
var countCookies = 27;
console.log(countCookies);
// iterate through all cookies
for (var i = 1; i < countCookies + 1; i++) {
var cookiename = "answer" + i;
// get content of cookie (is array of objects)
var answer = checkCookie(cookiename);
// iterate through content
for (var j = 0; j < answer.length; j++) {
// get value of object
var val = answer[j].value;
// get the input field (textarea or radio button)
var x = document.getElementById(answer[j].n).getElementsByTagName('input');
// if input is radio, then check the one at position stored in value of object
for (var k = 0; k < x.length; k++) {
if (x[k].type === "radio") {
x[val].checked = true;
// if textarea set its value to the one stored in object value
} else {
x[k].value = val;
}
}
console.log("j: " + j);
}
}
console.log(i);
}

Categories

Resources