-1

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Pedro Peña
  • 49
  • 1
  • 10

3 Answers3

0

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);
botem
  • 348
  • 1
  • 11
-1

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.

Sephirus
  • 16
  • 2
  • Well, it sounds like this is what I´m looking for, let me try the code and see what happens. Thanks!!!! – Pedro Peña Jan 12 '16 at 14:20
  • Yeap, it seems to work really nice. Thanks!! This really helps me! Shame that I´m new in town and I can´t rate the answers yet, but in case anybody is having the same issue, THIS IS THE CORRECT ANSWER.. – Pedro Peña Jan 12 '16 at 14:56
-1

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/>"));
Hsm Sharique Hasan
  • 203
  • 1
  • 3
  • 10