[英]Parameters and object literals in Javascript
I have a function where I am passing some values.我有一个传递一些值的函数。 I create an array and want to create two name/value pairs.
我创建了一个数组并想创建两个名称/值对。 The parameters valueField and displayField are strings which I am passing in.
参数valueField和displayField是我传入的字符串。
At the bottom where I am instantiating a comboStore, valueField and displayField are treated as parameters which is good.在我实例化组合存储的底部,valueField 和 displayField 被视为很好的参数。 However where I am pushing objects onto the dataArray, the valueField and displayField are not treated as parameters, but as literal values.
但是,在我将对象推送到 dataArray 的地方,valueField 和 displayField 不被视为参数,而是被视为文字值。
test:function (valueField, displayField, x, y) {
var dataArray = []
dataArray.push(
{
valueField: x, //this line does not use paramaters
displayField: y //this line does not use paramaters
}
)
var comboStore = {
fields: [valueField,displayField], //this line uses paramaters
data: dataArray
}
return comboStore;
},
How do I parameterise object literals like this?我如何像这样参数化对象文字?
I tried :我试过 :
'' + valueField + '': x
but that seems to not work.但这似乎不起作用。
Use subscript (or "bracket") notation instead of dot notation:使用下标(或“括号”)表示法而不是点表示法:
var data = {};
data[valueField] = x;
data[displayField] = y;
dataArray.push(data);
That works, but it is verbose.这有效,但它很冗长。 You could write a function to encapsulate the object creation logic:
您可以编写一个函数来封装对象创建逻辑:
function dataPoint(valueField, displayField, x, y) {
var data = {};
data[valueField] = x;
data[displayField] = y;
return data;
}
dataArray.push(dataPoint('a', 'b', 1, 2));
dataArray.push(dataPoint('c', 'd', 3, 4));
If your valueField
and displayField
properties are constant you could DRY up the code further with a factory function:如果您的
valueField
和displayField
属性是常量,您可以使用工厂函数进一步干燥代码:
function dataPointFactory(valueField, displayField) {
return function(x, y) {
var data = {};
data[valueField] = x;
data[displayField] = y;
return data;
}
}
var makeDataPoint = dataPointFactory('valueField1', 'displayField1');
dataPoint.push(makeDataPoint(1, 2));
dataPoint.push(makeDataPoint(3, 4));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.