通过组合字符串 & 来创建新的 JavaScript 变量多变的 [英] Make new JavaScript variable by combining string & variable
问题描述
所以这是我的问题.
pageTitle1 = ('This is page one');
pageTitle2 = ('This is page two');
pageTitle3 = ('This is page three');
currentPageTitle = ('pageTitle'+currentPosition);
$("#pageNumber").html(currentPageTitle);
我正在尝试根据我所在幻灯片的 currentPosition 在屏幕上显示当前页面标题.我遇到的问题是当我需要它显示这是第一页"时,上面的代码在屏幕上显示pageTitle1".我是 javascript 新手,所以我觉得这是一个简单的解决方案,但几天的谷歌搜索并没有给我带来任何好处.
I'm trying to display the current page title to the screen based on the currentPosition of the slide I am on. The issue I'm having is the code above is displaying "pageTitle1" to the screen when I need it to display "This is page one". I'm newish to javascript so I have a feeling this an easy fix but days of googling has yielded me nothing.
推荐答案
使用数组而不是单独命名每个变量.
Use an array instead of naming each variable individually.
var pageTitles = [
'This is page one',
'This is page two',
'This is page three'
];
var currentPageTitle = pageTitles[currentPosition];
您的代码不工作的原因是因为它只是简单地添加了两个字符串 "pageTitle"
和 currentPosition
并将连接后的字符串分配给 currentPageTitle代码>.您想要的是获取存储在具有该名称的变量中的值.假设您在全局范围内创建这些(顺便说一句,这不是一件好事),您可以这样做:
Reason why your code is not working is because it is simply adding the two strings "pageTitle"
and currentPosition
and assigning the concatenated string to currentPageTitle
. What you instead want is to get the value stored in the variable having that name. Assuming you are creating these in the global scope (which is not a good thing btw), you can do:
var currentPageTitle = window['pageTitle'+currentPosition];
然而,使用数组是更好的方法.
However, going with arrays is a better approach.
这篇关于通过组合字符串 & 来创建新的 JavaScript 变量多变的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!