0

I have two variables that I need to join and then print the value of a different variable which has the name of the variables I just joined.

I have:

var NoQ = "1234, 4321, 6789"

var NoQ1 = "Number: " + NoQ.slice(0,4);
var NoQ2 = "Number: " + NoQ.slice(5,9);

var i = 1 //i is in a for loop so i++

console.log(NoQ+i)  
//prints 1234, 4321, 67891

I want NoQ and i to join to technically become NoQ1 before logging.

Expected output: Number: 1234

How do I achieve this?

Any help is appreciated.

JackU
  • 1,406
  • 3
  • 15
  • 43
  • But `NoQ` is `"1234, 4321, 6789"`, so shouldn't the output be: `"number: 1234, 4321, 6789"` ? – nick zoum Feb 28 '19 at 09:30
  • No, because I want it to print `NoQ1` but joined `NoQ` and `i`. – JackU Feb 28 '19 at 09:31
  • Can you please post the full output you're expecting? It's unclear what you're asking. Do you want to split based on `,`? – adiga Feb 28 '19 at 09:32
  • Can you try and rewrite this question, it's not making much sense at the moment e.g. `to join to technically become` what do you mean `technically`? – StudioTime Feb 28 '19 at 09:34
  • Are you aware `console.log` can take several parameters which will be printed in row ? `console.log('one', 'two', 'three', 'four') // one two three four` – samb102 Feb 28 '19 at 09:36

5 Answers5

2

Better to use an Array for ordered items and return the value with an index.

The wanted type is not possible to get a variable in a variable for accessing a value.

var noQ = "1234, 4321, 6789",
    noQs = noQ.split(/,\s*/g).map(s => `Number: ${s}`);

console.log(noQs[0]);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Something like this ?

var NoQ = "1234, 4321, 6789";

var i = 1;

console.log('Number: ' + NoQ.split(', ')[i]);
0

You can access global variables on window so you can use array access syntax to access those variables with a string value:

var NoQ = "1234, 4321, 6789"

var NoQ1 = "Number: " + NoQ.slice(0,4);
var NoQ2 = "Number: " + NoQ.slice(5,9);

var i = 1 //i is in a for loop so i++

for (let i = 1; i <= 2; ++i)
  console.log(window['NoQ' + i]) 
James Coyle
  • 9,922
  • 1
  • 40
  • 48
0

Use a template string to build your output string and string.split() with a regex to split your input string on the commas and get rid of the extra space:

const NoQ = "1234, 4321, 6789"

const NoQi = i => `Number: ${NoQ.split(/,\s*/)[i - 1]}`

console.log(NoQi(1))
console.log(NoQi(2))
console.log(NoQi(3))
jo_va
  • 13,504
  • 3
  • 23
  • 47
-2

Try console.log(window['NoQ'+i]) NOT the best solution, but it is the closest to what you are trying to do.

JohnPan
  • 1,185
  • 11
  • 21