Generating new variables to save loop results - javascript

I´ll try to be very specific about this topic.
So I have a "for" loop in javascript working just fine. The loop aims to retrieve the URLs of all the files existing in a target folder. The question is, how can I save the retrieved URLs into individual variables?
So, in order to make things easy, I won´t paste the code I´m using, I´ll just create a simple array and run a "for" loop as an example, so you guys can tell me how you would try to save the results into new variables.
So here's the example:
var index;
var arrayElements = ["FirstURL", "SecondURL", "ThirdURL"]
for (index = 0; index < arrayElements.length; index++) {
document.write (arrayElements[index]+"<br/>");
}
So, with that code, I can "print" the different URLs included in the array (I could use console.log of course, but I´m writing in notepad++, so I have to test the code with document.write)
So the question, how can I save each URL into an individual variable?
EDIT:
Ok, so reading the first answers, I think I must clarify some things.
The question is that I need to store the URLs in variables so I can call them later. So it´s not a question about "printing" the URLs.

The function eval()
I know eval is bad
var data = ["a", "b", "c"];
function makeIndvidualVariable(array){
var size;
try{
size = array.length;
for(var i = 0 ; i < size ; ++i){
if( eval(array[i]) != undefined){
eval("var "+array[i]+"="+array[i]+";");
}else{
throw "already exist variable : "+array[i];
}
}
}catch(e){
console.log(e);
}finally{
array = size = i = null;
}
}
makeIndvidualVariable(data);

You can obtain individual variables with window object (if i got you properly).
Use the thing with JS that enables you to declare variables in window scope.
var index;
var arrayElements = ["FirstURL", "SecondURL", "ThirdURL"]
for (index = 0; index < arrayElements.length; index++) {
window['variable'+index] = arrayElements[index];
}
// now variables are available globally (through window object)
document.write(variable0); // prints FirstURL
document.write(variable2); // prints ThirdURL
// etc.
Hope this helps.

Just for the sake of printing the urls stored in array one by one and avoid loops you can use this:
document.write (arrayElements.join("<br/>"));

Related

Arrays are causing me problems

So. Started arrays. Yeah went as well as the loops did. And as a result, I need help.
/*jshint multistr:true */
var text = "Yo yo yo, what's / good fam. My name is / Caleb, my dude.";
var myName = "Caleb"
var hits = []
for(var i = 0; i >= text.length; i++){
if(text[i] === 'C') {
}
for(var j = i; i <= i + myName.length; i++){
}
}
That is the exact code that I have. Now, What it needs to do is search for my name within the confines of the text string. Only problem is that its saying that "It looks like your second 'for' loop isn't pushing values to the hits array. Make sure it's working properly and that myName's text appears somewhere in the text variable." This is a CodeAcademy project. I'm just not understanding. If someone could help me with this, I would really appreciate it.
Thanks!
First of all make sure you have all the semicolons right. Also, add some action in case the loop gets a result!
Also, i don't think you have defined var j, did you?
Finally - if it's asking u to push some values into hits array, then use this push method:
hits.push();
To help u i'd need deeper understanding of the task itself. what did u have to do, what were u starting with?
Edit:
var myName = "Caleb"; // define myName before text so it can be used in text
var text = "Yo yo yo, what's / good fam. My name is / "+myName+", my dude."; // define text and use myName variable between two strings, connected with +
var hits = []; // define hits array
for(var i = 0; i < text.length; i++) { //start loop, make sure second parameter is not infinite or it would crash your browser
if(text[i] === 'C') { // if found i that corresponds with 'C'
var letterLocation = i; // set variable letterLocation with value of 'C' position
hits.push(i); // add the location number to hits array with .push method
};
};
console.log(hits); // display hits array in console
Here's some working code for you, just follow the task and change whatever is necessary - hope it helps.
Generally - i changed the order of variables, so that u can use myName in text, also made the for loop print out the position of letter C and push this value into the hits array. Is that what u meant?

How to Edit and Remove item from sessionStorage

This code to store items in sessionStorage so i want to add, edit ,
remove item and remove all my code worked well except remove item i
don't know the reason
function clearItem () {
for (var i = 0; i < sessionStorage.length; i++) {
var a = sessionStorage.key(i);
var b = sessionStorage.removeItem(a);
}
}
here's my code in jsfiddle
function clearItem () {
for (var i = 0; i < sessionStorage.length; i++) {
var a = sessionStorage.key(i);
sessionStorage.removeItem(a);
}
}
You have several problems:
You have indicated that you only want to remove the phone number from sessionStorage here. In this case, there is no need to loop over sessionStorage at all. Just remove that one entry:
sessionStorage.removeItem("number");
In looking over the Fiddle that you provided, your code was quite disorganized and didn't make much logical sense from a "flow" perspective. I have modified it to a working version available here. The biggest issues with your code was that you are trying to loop over sessionStorage when saving and retrieving the values, when what you should have been doing is simply creating key/value pairs of data and accessing the data with the key names you've created.
Read about sessionStorage here

Why Runtime error if input array element are parsed to integer altogether in javascript?

I was working on counting sort1 problem on hackerrank. I am using JavaScript to solve the problem.
Standard input is providing a number and an array which I was reading like this
var inp = input.split('\n')
var n = parseInt(inp[0]); //Number of elements
var ar = inp[1].split(' ').map(function(item){
return parseInt(item);
}); //Array of numbers.
I was using above code in almost all of my solutions, it always worked.
Then I process the above array ar in for loop which is giving runtime error in one of the test cases(last testcase).
for(var i = 0; i < n; i++) {
var number = ar[i];
//more code
}
But if I don't parse elements of the array using map function but parse them later in for loop, one by one, I don't get any error.
var ar = in[1].split(' '); //Array of numbers in string format
for(var i = 0; i < n; i++) {
var number = parseInt(ar[i]);
//more code
}
Can Anyone explain Why?
in is a keyword, and you are trying to use it as a variable. I'm not sure why it says "Runtime Error", since this is actually a parsing error. Once renamed to something else, I could run the first two paragraphs error-free.
The only problem I remember having on Hackerrank that the .split() method often gave an empty string ("") as the last element of the array. Probably that's why you failed on the last test case.
Make your logic like:
if(arr[i] !== "")
// perform operations
else
break;
Also, you can't use in as a identifier because it is a reserved keyword.

Javascript: TypeError variable is undefined

I am currently building a small web application with similar functionality across all modules. I want to code small generic functions so that all programmers next to me, call these functions and these functions return necessary but important data for them to implement their functionality. In this example, I am trying to deal with the typical "choose true or false" exercise. So from the template.php they call this function:
function checkAnswers(){
var radiobuttons = document.form1.exer1;
var correctAnswers = answers(); //this is an array of string
var checkedAnswers = checkExerciseRB(radiobuttons, 2, correctAnswers);
for(i=0; i<checkedAnswers.length; i++){
alert(checkedAnswers[i]);
}
}
Function checkExerciseRB is my generic function, it is called from checkAnswers.
function checkExerciseRB(rbuttons, opciones, correct){
var answers = new Array();
var control = 0;
for(i=0; i<rbuttons.length; i++){
var noPick="true";
for(j=0; j<opciones; j++){
if(rbuttons[control+j].checked){
if(rbuttons[control+j].value==correct[i]){
answers[i]= 1;
noPick="false";
break;
}
else{
answers[i]=2;
noPick="false";
break;
}
}
}
if(noPick=="true")
answers[i]=0;
control=control+opciones;
}
return answers;
}
It works great but while looking at my favorite browsers (FireFox, Chrome) error log it says:
TypeError: rbuttons[control + j] is undefined
Any clue on how to deal with this matter?
This probably means that control + j is greater than or equal to the length of the array rbuttons. There's no such array element as rbuttons[control + j].
You should learn how to use the JavaScript debugger in your favorite browsers! Debuggers are great. They let you watch this code run, line by line, as fast or as slow as you want, and watch how the value of control changes as you go.
You’ll watch it, and you’ll think “Oh! That line of code is wrong!”
You're looping through rbuttons.length times, but in each loop you're adding 2 to control. Using control to index your array, you're going to run past the end.
Does the index specified by control + j exist in the array? i.e: If that evaluates to 4, is there at least 5 items in the array?
Also, you should be using var i, var j, etc inside your for loop. Without it your variables are leaking into the scope this code is executed in (most likely the global scope, and that's not good) :)

Changing values of each object in Javascript

What is the best way to add the additional path information to each javascript object? Like "assets/img/upload/" before each jpg name? That I have url="assets/img/upload/02.jpg" etc.? That would be great help!
My data right now:
[Object { url="02.jpg"},
Object { url="03.jpg"},
Object { url="09.jpg"},
Object { url="04.jpg"},
Object { url="5.jpg"}
...]
A simple for loop:
for(var i = 0; i < array.length; i++)
{
array[i].url = "assets/img/upload/" + array[i].url;
}
Suppose your array of objects is called MyArray:
for (var i = 0, LoopTimes = MyArray.length; i < LoopTimes; i++) {
MyArray[i].url = "assets/img/upload/" + MyArray[i].url;
}
Note that:
a) the opening curly brace goes on the same line as the for statement. See Crokfod on Javascript The Good Parts on youtube for the explanation. In javascript, putting the opening brace on the next line can create some weird bugs that are hard to detect.
b) I cache the length of MyArray in LoopTimes so that I don't have to evaluate the length of the array at every iteration.
If you are only going to be running this code in a modern browser, you could always consider using the map method of the Array object.
Assuming your array of objects is called "array"
array.map(function(item) {return item.url = "assets/img/upload/" + item.url;});
This runs the anonymous function, that takes an "item" in the array, and returns the modified url field, over each element of the array.
If you need your code to run on older browsers, stick with the for loops suggested by the other contributors.

Categories

Resources