0
var greentext='shopping';
var colors=new Array('green','blue','red','violet','brown');
for(i=0;i<colors.length;i++)
{
 //suppose consider colors[i] is green
}

When concatenating colors[i]+'text' and passing to some div using innerHTML, the string   "greentext"  is passed rather than the value of the concatenated string "shopping". How to pass the value of dynamically created string as above?

Hope my question is clear.....please help me

2
  • How are you trying to assign the value? Please update your example. Commented Jul 8, 2012 at 13:32
  • I tried to assign value as document.getElementById('somedivname').innerHTML=colors[i]+'text'; Commented Jul 8, 2012 at 14:55

1 Answer 1

3

I'd do it completely differently:

  var text = {
    green: 'shopping',
    blue: 'contemplating infinity',
    red: 'cooking beans',
    violet: 'writing poetry'
  };

  var colors = ['green', 'blue', 'red', 'violet' ];
  for (var i = 0; i < colors.length; ++i) {
    alert( text[ colors[i] ] );
  }

Structured data should preferably be represented with actual structures in whatever programming language you're using. JavaScript is flexible enough that you can "construct" variable names, but it's not idiomatic. Here, I've made a simple object with properties corresponding to your colors.

Sign up to request clarification or add additional context in comments.

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.