0

Is it possible to use varName1[varName2] to retrieve a value from an array. In the example below, .el is a select box, thisVal might = 2 and thisName = 'B' which should result in the answer 'U' in fact I am getting undefined

<script>
var A = ['B','B','Z','Z']
var B = ['C','O','U','C2','C3','D']
var C = ['D','Z','D','Z']
  $('.el').on('change', function() {
    var thisVal = this.value
    var thisName = this.name
    var nextName = thisName[thisVal]
    alert( nextName );
  })
</script>

2 Answers 2

5

If you arrays are in the global scope, you can use.

window[thisName][thisVal]

Example

var A = ['B','B','Z','Z'];
var B = ['C','O','U','C2','C3','D'];
var C = ['D','Z','D','Z'];

var thisVal = 2;
var thisName = 'B';

console.log(window[thisName][thisVal]);

As an alternative you can use an object to store your arrays and instead of the window use your object.

Example

const obj = {
  A: ['B','B','Z','Z'],
  B: ['C','O','U','C2','C3','D'],
  C: ['D','Z','D','Z']
}

const thisVal = 2;
const thisName = 'B';

console.log(obj[thisName][thisVal]);

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

Comments

0

which should result in the answer 'U' in fact I am getting undefined

That is not applicable for javascript and undefined is exactly what it should return

You can use javascript eval for this purpose

var a = [1, 2, 3];
var x= 'a';
var y=2;
console.log(x+'['+y+']')  // "a[2]"
console.log(eval(x+'['+y+']'))  // 3

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.