加入变量名称

时间:2016-06-02 06:26:29

标签: javascript jquery

我有多个长变量名称。

var easternstateconventionlocation = "someting a";
var easternstateconventiondateandtime = "someting b";
var easternstateconventionsponsor = "someting c";

正如您所见,easternstateconvention很常见。当我使用这些变量时,是否可以使用公共部分+附加部分并组合来创建完整的变量名称?例如:

var common = 'easternstateconvention';
var loc = 'location';
var spo = 'sponsor';
var dat = 'dateandtime'; 
.text('location: '+ common +''+loc+' at '+ common +''+dat);

我的要求是缩短变量名称以备将来使用。

注意:我正在寻找一种解决方案来做到这一点,而无需更改现有的长变量名称。

3 个答案:

答案 0 :(得分:3)

您可以创建一个包含变量的对象,然后您可以使用Bracket notation从对象中获取数据。

var obj = {
  easternstateconventionlocation: "someting a",
  easternstateconventiondateandtime: "someting b",
  easternstateconventionsponsor: "someting c"
}


var common = 'easternstateconvention';
var loc = 'location';
var spo = 'sponsor';
var dat = 'dateandtime';

console.log('location: ' + obj[common + loc] + ' at ' + obj[common + dat])

答案 1 :(得分:1)

var common = 'easternstateconvention';
var loc = 'location';
var spo = 'sponsor';
var dat = 'dateandtime'; 
console.log('location: '+ [common] +''+[loc]+' at '+ [common] +''+[dat]);

Demo

答案 2 :(得分:0)

var common = {
    location: "someting a",
    dateandtime: "someting b",
    sponsor: "someting c"
 };

var loc = 'location';
var spo = 'sponsor';
var dat = 'dateandtime'; 
console.log('location: '+ common[loc]+' at '+ common[dat]);

var common = {
    location: "someting a",
    dateandtime: "someting b",
    sponsor: "someting c"
 };

console.log('location: '+ common['location']+' at '+ common['dateandtime']);

但你使用CamelStyle。 String或varialbe' dateAndTime'它可以从&date; time&time'。

中读取