3

i repeat the title because everything is there : How to pass a variable in array index

var xyz = 0;
var somearray = ['a','b','c'];
var content = somearray[xyz]; - **that dont work !**

what should be the RIGHT way to do that ?

2
  • actually the above does work (at least in my test in firebug I get content = 'a'). What about the above isn't working for you? Commented Jan 26, 2011 at 22:55
  • works heres a demo Commented Jan 26, 2011 at 22:55

2 Answers 2

1

Just a stab in the dark here, but perhaps the OP is using inArray and might be asking (indirectly) how to get the intellisense working in whatever tool they're using.

If that's the case, I'm sure someone here can provide a more elegant solution but something similar to the following should work:

var somearray = ['a','b','c'];
var index = $.inArray('a', somearray);
if (index > -1) {
    index = isNaN(index) ? 0 : index;
    var content = somearray[index];
}
Sign up to request clarification or add additional context in comments.

1 Comment

A helpful answer, but inferring a lot more from the question than I think one can so it seems as though you are offering a really helpful answer to a different question.
0

That actually is correct. After executing your code, minus the comment, content contains 'a'.

<html>
<head>
   <title>Test</title>
</head> 
<body>
<script type="text/javascript"> 
    var xyz = 0;
    var somearray = ['a','b','c'];
    var content = somearray[xyz];
    alert(content);
</script>
</body>
</html>

You should get a nice little alert box that says "a".

1 Comment

Did you cut and paste your actual code into your question? Or retype it? You might have a typo in your running source, or a mis-cased character.

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.