简体   繁体   中英

push javascript variable into array

I have 2 global variables that I would like to use in place of YYYYYY and XXXXXX but cant seem to figure out how to make it happen. Can anyone offer a suggestion? Thanks

var channelKeys = [];
channelKeys.push({
  channelNumber: YYYYYY,
  name: 'Location1',
  key: 'XXXXXX',
  fieldList: [{
    field: 1,
    axis: 'T'
  }, {
    field: 2,
    axis: 'T'
  }, {
    field: 3,
    axis: 'T'
  }]
});
Global Variables:
var var1='test'
var var2='test1'

We Can assign the value after intialization of channelKeys like:

channelKeys[0].channelNumber=x;
channelKeys[0].key=x;

or can be intialized with channelKeys:

var channelKeys = [];
channelKeys.push({
  channelNumber: var1,
  name: 'Location1',
  key: var2,
  fieldList: [{
    field: 1,
    axis: 'T'
  }, {
    field: 2,
    axis: 'T'
  }, {
    field: 3,
    axis: 'T'
  }]
});

You can go with below kind of stuff. Are you expecting something else ?

var firstVariable = 'YYYYY';
var secondVariable = 'XXXXX';
var channelKeys = [];
channelKeys.push({
  channelNumber: firstVariable,
  name: 'Location1',
  key: secondVariable,
  fieldList: [{
    field: 1,
    axis: 'T'
  }, {
    field: 2,
    axis: 'T'
  }, {
    field: 3,
    axis: 'T'
  }]
});

If you are looking to loop in to the array and replace you can use like the below. If both the first and second variables should be array with same length, You can use the index as [index] near the first and Second variable name.

$.each(channelKeys, function(index){
channelKeys[index].channelNumber = firstVariable;
channelKeys[index].key= secondVariable;

});

Global variables can be assigned to channelKeys like:

var XXXXXX=12;
var YYYYYY =34;

var channelKeys = [];
channelKeys.push({
  channelNumber: YYYYYY,
  name: 'Location1',
  key: XXXXXX,
  fieldList: [{
    field: 1,
    axis: 'T'
  }, {
    field: 2,
    axis: 'T'
  }, {
    field: 3,
    axis: 'T'
  }]
});

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