【问题标题】:Make new JavaScript variable by combining string & variable通过组合字符串和变量创建新的 JavaScript 变量
【发布时间】:2011-06-25 22:54:27
【问题描述】:

所以这是我的问题。

pageTitle1 = ('This is page one');
pageTitle2 = ('This is page two');
pageTitle3 = ('This is page three');

currentPageTitle = ('pageTitle'+currentPosition);

$("#pageNumber").html(currentPageTitle);

我正在尝试根据我所在幻灯片的 currentPosition 在屏幕上显示当前页面标题。我遇到的问题是上面的代码在我需要显示“这是第一页”时在屏幕上显示“pageTitle1”。我对 javascript 很陌生,所以我觉得这很容易解决,但谷歌搜索的日子对我没有任何帮助。

【问题讨论】:

  • 或者你可以简单地改变 currentPageTitle = ('pageTitle'+currentPosition); to currentPageTitle = eval('pageTitle'+currentPosition);

标签: javascript string variables var


【解决方案1】:

做这样的事情。

var pageTitle = new Array();
pageTitle.push('This is page one');
pageTitle.push('This is page two');
pageTitle.push('This is page three');

currentPageTitle = (pageTitle[currentPosition]);
$("#pageNumber").html(currentPageTitle);

或者干脆使用 eval (really super unrecommended)

var currentPageTitle = eval('pageTitle'+currentPosition);

【讨论】:

  • 为时已晚 :) 无论如何都是另一种方式。
【解决方案2】:

无需任何其他修改,即可替换此行

currentPageTitle = ('pageTitle'+currentPosition);

用这个:

currentPageTitle = window['pageTitle'+currentPosition];

【讨论】:

    【解决方案3】:

    使用数组而不是单独命名每个变量。

    var pageTitles = [
     'This is page one',
     'This is page two',
     'This is page three'
    ];
    
    var currentPageTitle = pageTitles[currentPosition];
    

    您的代码不起作用的原因是因为它只是添加了两个字符串"pageTitle"currentPosition 并将连接的字符串分配给currentPageTitle。相反,您想要的是获取存储在具有该名称的变量中的值。假设您在全局范围内创建这些(顺便说一句,这不是一件好事),您可以这样做:

    var currentPageTitle = window['pageTitle'+currentPosition];
    

    但是,使用数组是更好的方法。

    【讨论】:

    • @Mike:如果这个答案解决了您的问题,您应该通过单击问题左侧的空心绿色复选标记将其标记为“已接受”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-28
    • 2023-03-12
    • 1970-01-01
    • 2020-12-16
    • 2021-10-18
    • 2014-12-25
    相关资源
    最近更新 更多