0

This question has been asked before, I wanted to create a (possibly) simpler version for others to (maybe) understand easier.

What I wanted to do was combine a string with the data (string) from a variable to create a variable name. I suppose it would be called a dynamic variable?

In this example I want to add a class and text to a div..

<div class="time fa"></div>

..based on changing data which I get from a json file.

var timetain = 10;
var timebus = 20;
var icontrain = 'fa-train';
var iconbus = 'fa-bus';
var type = 'bus'; // this string comes from a json file, it will either be train or bus

So I want to add the word time to the data from the variable named type to output the data from either timetrain or timebus

$('.time').text('Travel by bus will take |'time'|+|type| minutes');
$('.time').addClass(|'icon'|+|type|));

I suppose another way of wording the question would be "How to combine a variable's data with a string to get the data from a third variable with Javascript?"

4
  • LOL - meta.stackexchange.com/a/19492/256963 Commented Jul 2, 2017 at 8:54
  • @vsync Dumb guys like jQuery and really dumb guys that have bumped their head a lot (me) can barely use/understand it or differentiate it from javascript. I should also mention that my terminology is just as bad as my fundamental misunderstanding of all things code related and anything that requires more than a grade 3 education to comprehend including (but not limited to) tying my own shoes. (I tell people I just like the sound of velcro, but between you and I, that's a lie) Commented Jul 2, 2017 at 9:15
  • 1
    @vsync With that said, I thank you for your time spent answering and apologize for the time it took for me to get around to reading/understanding/upvoting it :) Commented Jul 2, 2017 at 9:15
  • I can only hope my answer really helped in your case Commented Jul 2, 2017 at 9:35

4 Answers 4

2

Using ES6 template literals:

var time = "30",
    typesArr = ["bus", "train", "foot"],
    type = typesArr[ Math.random()*typesArr.length|0 ]; // pick random array item

// mix values with strings:
document.write(   `Travel by ${type} will take ${time} minutes`   );

Basically you cannot construct a variable name in javascript, unless it is an Object's Key, so you have to store the keys in some object in order to access them, but in your case it's much easier:

$('.time').addClass('icon fa-' + type); // example => 'icon fa-train'

But if you really wanted to construct the keys dynamically you could do:

var types = {
    train : "fa-train",
    bus : "fa-bus"
};

var whatever = "bus";
var type = types[whatever];  // "fa-bus"
Sign up to request clarification or add additional context in comments.

Comments

1

Why not make an associative array of the times?

time = {'bus': 20, 'train': 10}

etc.? Than just access it with time[type]. This is much safer than what you want to do (you would have to rely on eval), which seems like overkill for this.

2 Comments

Really no concept of "associative array" in javascript ... better to call it what it is ...an object literal
@charlietfl as a language-ignorant description, it describes it perfectly
1

Nicht so @Hastig, lieber ordentlich machen.

A better solution without using Eval:

Most programming languages nowadays support a data-structure to "group" variables that belong together. It's called an Object. I can't come up with a single disadvantage in using Objects over multiple variables. This approach is even (a teeny tiny bit) faster than your attempt with eval().

var configByType = {
  "train": {
  label: "train",
    time: 10,
    icon: "fa-train"
  },

  "bus": {
    label: "bus",
    time: 20,
    icon: "fa-bus"
  }
}

function travel(type){
  //because creating and adding a new `span` is simpler 
  //than checking wich classes to remove on `.time.fa`
  var $span = $('.time').html('<span>').children();
  
  if(type in configByType){
    let config = configByType[type];
    $span.addClass(config.icon)
      .text('Travel by '+ config.label +' will take ' + config.time + ' minutes')
  }else{
    
    $span.text('unsupported type: ' + type);
  }
}

$('#update').click(function(){
  var types = ["car", "bus", "train", "plane"];

  var randomType = types[Math.floor(Math.random() * types.length)];
  travel(randomType)
});

travel('bus');
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="time fa"></div>
<br>
<input id="update" type="button" value="update" />

Comments

-3

A Solution Using Eval

eval('string' + variableName)

Applied To Provided Code

var timetain = 10;
var timebus = 20;
var icontrain = 'fa-train';
var iconbus = 'fa-bus';

var type = 'bus'; // this data (string) comes from a json file, it will either be train or bus

$('.time').text('Travel by bus will take ' + eval('time' + type) + ' minutes');
$('.time').addClass(eval('icon' + type));
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="time fa"></div>

Note

Before using this solution be sure to read more about the criticisms of using eval

This solution works and addresses the question as asked. I assume the downvotes are because of the criticisms that I pointed out and that there are better ways to go about things if properly planned but we'll never know because nobody cared to explain themselves.

I needed the simple eval way because I was putting together a complicated web of different json file comparisons for a simple game app and needed a quick and easy 'variable-variable', php-style method as placeholder code until I was able to better think everything through.

In the more advanced versions I am using objects and arrays like recommended in the other answers here but I was unable to think through things without using eval as temporary 'scaffolding'.

Fiddle

https://jsfiddle.net/Hastig/o169ja8w/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.