-4

I want to get value name + id.But how ?

var samin1 = "Cat";
var samin2 = "Dog";
var samin3 = "Elephant";
var samin4 = "Wolf";

var choosenvalue = 2;

var outputvalue = "samin"+"choosenvalue";

So I need to see "Dog".But I see as text "samin2"; Note: I dont use array.

MattisS
  • 5
  • 2
  • Do ```var outputvalue = `${ samin2 }${ choosenvalue }`;``` – Sebastian Waldbauer Jan 20 '19 at 16:59
  • 1
    The code you posted would produce `"saminchoosenvalue"`, not `"samin2"`. It's not really clear what you're trying to do, but it sounds very much like you want to learn about [arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) instead of naming your variables this way. – elixenide Jan 20 '19 at 17:00
  • Seems to me like MattisS is trying to dynamically access a variable. This makes no sense. You could do it if the variables were in an array or object. – Joshua Obritsch Jan 20 '19 at 17:02

3 Answers3

3

Using the keyword var adds the variable to the global window object.

Mdn var:

The scope of a variable declared with var is its current execution context, which is either the enclosing function or, for variables declared outside any function, global. If you re-declare a JavaScript variable, it will not lose its value.

var samin1 = "Cat";
var samin2 = "Dog";
var samin3 = "Elephant";
var samin4 = "Wolf";

var choosenvalue = 2;

var outputvalue = window["samin"+choosenvalue];

console.log(outputvalue);
kemicofa ghost
  • 16,349
  • 8
  • 82
  • 131
2

I am not sure why would you need this, but it's possible to do using eval

var samin1 = "Cat";
var samin2 = "Dog";
var samin3 = "Elephant";
var samin4 = "Wolf";

var choosenvalue = 2;

var outputvalue = eval("samin" + choosenvalue);

console.log(outputvalue);

Have you considered to use an array to store values instead?

var animals = [
  "Cat",
  "Dog",
  "Elephant",
  "Wolf",
]

var choosenvalue = 1;

console.log(animals[choosenvalue]);
antonku
  • 7,377
  • 2
  • 15
  • 21
0

I suggest use object. You should not use eval() read here

And also avoid using global variables too. read here

 let obj = 
 {'samin1' : "Cat",
'samin2': "Dog",
'samin3': "Elephant",
 'samin4': "Wolf"
 }

var choosenvalue = 2;

var outputvalue = obj[`samin${choosenvalue}`]

console.log(outputvalue)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60