最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Appending string to variable name - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question edited Nov 24, 2011 at 18:01 Dave Newton 160k27 gold badges260 silver badges307 bronze badges asked Nov 24, 2011 at 17:58 user823527user823527 3,71217 gold badges69 silver badges111 bronze badges 3
  • 5 Normally when I think I need to change a variable name like this, I realise the easiest thing is to use an array instead – ChrisW Commented Nov 24, 2011 at 18:00
  • is this what you want? card_id=3 card_links_grid1 card_links_grid2 card_links_grid3 are 5,6 and 7 respt but when you card_links_grid+card_id you want it to return 7?? am i correct? – Baz1nga Commented Nov 24, 2011 at 18:03
  • An object will do what I am looking for. – user823527 Commented Nov 24, 2011 at 20:23
Add a ment  | 

3 Answers 3

Reset to default 8

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.

I also remend 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/Q2rVH/

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

you could use the eval method for the same and get away with it.. something like this

var card_id=3;

var card_links_grid1=5,card_links_grid2=6,card_links_grid3=7;

eval("card_links_grid"+card_id) //will  o/p 7

P.S: If I ustood the question correctly

发布评论

评论列表(0)

  1. 暂无评论