简体   繁体   中英

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.

At the bottom where I am instantiating a comboStore, valueField and displayField are treated as parameters which is good. However where I am pushing objects onto the dataArray, the valueField and displayField are not treated as parameters, but as literal values.

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:

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM