我正在将对象传递给函数。下面的简化示例:
countyInfo(sales.NY2008);
对象是:
{countyName:"Albany",percentage:0.864789889,percentageComparison:40.18903649,sales:1222},
{countyName:"Allegany",percentage:0.789529462,percentageComparison:27.98874729,sales:149},
{countyName:"Broome",percentage:1.009475302,percentageComparison:63.64364553,sales:880},
{countyName:"Cattaraugus",percentage:0.874885092,percentageComparison:41.82554597,sales:276},
{countyName:"Cayuga",percentage:0.801267677,percentageComparison:29.89160156,sales:268},
{countyName:"Chautauqua",percentage:0.830185925,percentageComparison:34.5794701,sales:455},
{countyName:"Chemung",percentage:0.744919757,percentageComparison:20.75717391,sales:272},
{countyName:"Chenango",percentage:1.191003494,percentageComparison:93.07074993,sales:242},
{countyName:"Clinton",percentage:0.767315265,percentageComparison:24.38765663,sales:265},
{countyName:"Columbia",percentage:0.83461736,percentageComparison:35.29783949,sales:260},
{countyName:"Cortland",percentage:1.144086442,percentageComparison:85.46513794,sales:234},
效果很好。
现在,我想由变量组成此参数。
var getLocation = "NY";
var getYear = "2008";
var getParameter= getLocation + getYear;
countyInfo(sales.getParameter)
在传递字符串时它不起作用。但是怎么办呢?
答案 0 :(得分:3)
只需更改代码即可使用括号符号访问对象属性,而不是使用点符号
var getLocation = "NY";
var getYear = "2008";
var getParameter= getLocation + getYear;
countyInfo(sales[getParameter]);
点符号:
括号符号
有关详细说明,请参考-
https://codeburst.io/javascript-quickie-dot-notation-vs-bracket-notation-333641c0f781
答案 1 :(得分:2)
由于sales
似乎是一个对象,因此可以使用索引符号来访问成员。
也就是说,sales.NY2008
等同于sales["NY2008"]
。
所以,只需做
countyInfo(sales[getLocation + getYear]);