JavaScript 中的变量赋值 [英] Variable assignment in JavaScript

查看:33
本文介绍了JavaScript 中的变量赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个js函数

我想给一个变量赋值

我的变量在 forloop 中

my variable is in a forloop

我有两个变量

即;

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

下面是我的js函数

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')

}
}

我的问题在这里

var theurl=spcd_+i;

我想将 theurl 值更改为 spcd_1spcd_2

I want to change theurl value to spcd_1 and spcd_2

如何在 for 循环中正确分配

how to assign this correctly in the for loop

var theurl=spcd_+i;

谁能告诉我正确的方法.

can any one show me the correct method.

谢谢

推荐答案

听起来您想要索引一个数组,而不是试图将自己连接到一个变量名.这是您修改的代码

Sounds like you want to index an array, rather than trying to concatenate yourself up a variable name. Here's your code modified

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 中的对象也可以是关联数组,这意味着您可以使用数组语法来创建并检索任意属性

Just for giggles, here's how you could keep using concatenation to get to your variable name. Objects in javascript can also be associative arrays, meaning you can use the array syntax to create and retrieve arbitrary properties

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

这篇关于JavaScript 中的变量赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆