JavaScript variable assignment

I have a js function

I want to assign a variable to a variable

my variable is in forloop

I have two variables

t

var spcd_1= "http://www.colbridge.com";
var spcd_2 = "http://www.google.com";

below is my js function

function openNewWindow(spcd) {
//alert("hello");
var tt = spcd;
alert(tt);
var i=0;
var spcd_1= "http://www.colbridge.com";
var spcd_2 = "http://www.google.com";
for(i=1;i<3;i++)
{
var theurl="'spcd_'+i";
 popupWin = window.open(theurl,
 '_blank',
 'menubar, toolbar, location, directories, status, scrollbars, resizable, dependent, width=640, height=480, left=0, top=0')

}
}

my problem is here

var theurl=spcd_+i;

I want to change the value theurlto spcd_1andspcd_2

how to properly assign this in a for loop

var theurl=spcd_+i;

can anyone show me the correct method.

thank

0
source share
5 answers

It looks like you want to index the array, rather than trying to combine the variable name. Here your code is changed

function openNewWindow(spcd) {
    //alert("hello");
    var tt = spcd;
    alert(tt);
    var i=0;
    var spcds = [];
    spcds.push("http://www.colbridge.com");
    spcds.push("http://www.google.com");
    for(i=0;i<spcds.length;i++)
    {
        var theurl=spcds[i];
        popupWin = window.open(theurl,
        '_blank',
        'menubar, toolbar, location, directories, status, scrollbars, resizable, dependent, width=640, height=480, left=0, top=0')

    }
}

, , . javascript ,

    var spcds = {};
    spcds['spcd_1'] = "http://www.colbridge.com";
    spcds['spcd_2'] = "http://www.google.com";
    //...
    var theurl = spcds['spcd_' + i];
0

, URL- .

Javascript ,

var urls = ["link1","link2","link3"]; //Add as many urls you need here

for: loop it

for (var i=0;i<urls.length;i++) {
//logic here
window.open(urls[i], '_blank',
 'menubar, toolbar, location, directories, status, scrollbars, resizable, dependent, width=640, height=480')
//Do your thing
}
+6

, :

var urls = [ "http://www.colbridge.com", "http://www.google.com" ];

for(var i = 0; i < urls.length; i++) {
    window.open(urls[i], '_blank',
     'menubar, toolbar, location, directories, status, scrollbars, resizable, dependent, width=640, height=480')
}

, Javascript.

+5

:

var my_var = "spcd_" + i;
0

window["theurl_"+i];

since global variables are window properties, and you can get properties using either dot notation or parenthesized notation.

But don't do it. :-)

The reason for not trying to do what you are doing is that JavaScript does not have block coverage, so placing wars anywhere but at the beginning of functions can lead to confusion. Sooner or later you get into trouble if you place variable declarations at the beginning of loops or conditional blocks.

0
source

All Articles