Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending string to variable name

Is there a way to define variables in javascript to append them with another variable?

var card_id;
var card_links_grid+card_id;

I'd like the second variable to be appended with the information found in the first variable. For each card_id there will be a card_links_grid. I want to be able to access the card_links_grid variable for a specific card_id.

What's the right way to do that?

like image 534
user823527 Avatar asked Nov 24 '11 17:11

user823527


2 Answers

The right was is to use either an array or an object, depending on if the id is going to be sequential or named.

var card_links_grid = {};
var card_id = "the_hanged_man";
card_links_grid[card_id] = "some value";

or

var card_links_grid = [];
card_links_grid.push("some value");

Variable variables are possible, but only with some hard to maintain and debug approaches that should be avoided. Use object types designed for the data structure you want to represent.

like image 104
Quentin Avatar answered Oct 09 '22 02:10

Quentin


I also recommend to use either array or object. But if you want to try with variable variable approach, you can try like this.

var card_id=1;
window['card_links_grid_' + card_id] = 'Marco';
document.write(window['card_links_grid_' + card_id]);

http://jsfiddle.net/Q2rVH/

Ref: http://www.i-marco.nl/weblog/archive/2007/06/14/variable_variables_in_javascri

like image 29
Thein Hla Maw Avatar answered Oct 09 '22 03:10

Thein Hla Maw