0

I have some arrays defined in js, and I want to use the variable's value to select which array should I select.

// My arrays
var battery = [123, 321, "", ""];
var cables = [234, 432, "", ""];

$(document).ready(function() {

    var file = "battery.jpg";
    var item = file.slice(0, -4); // item = "battery"

    console.log($(item)[0]); // undefined and I was hoping to log "123" - battery[0]
});
zee
  • 359
  • 3
  • 16
  • 2
    possible duplicate of ["Variable" Variables in Javascript?](http://stackoverflow.com/questions/5187530/variable-variables-in-javascript) – Gergo Erdosi Jun 02 '14 at 01:34

2 Answers2

1

You could use a bidimensional array.

//var mydata=Array()
mydata["battery"] = [123, 321, "", ""];
mydata["cables"] = [234, 432, "", ""];

$(document).ready(function() {

  var file = "battery.jpg";
  var item = file.slice(0, -4); // item = "battery"

  console.log(mydata[item][0]); // undefined and I was hoping to log "123" - battery[0]
});

EDIT: As pointed in the comment by Dalorzo it's not an array. I'll keep the mistake (commented) for comments coherency.

miguel-svq
  • 2,136
  • 9
  • 11
  • 2
    `mydata` is not an array is an object. `mydata=Array()` seems unnecessary – Dalorzo Jun 02 '14 at 01:35
  • javascript does not have associatve arrays as @Dalorzo pointed out. Answer is acheiving desired results but is not accurate regarding array vs object see: http://jsfiddle.net/aFMhx/ – charlietfl Jun 02 '14 at 01:57
  • Rigth @Dalorzo, in javascript there are arrays and objects, associative arrays do not exists... But could be someway confusing for a newbie use the right name. Anyway: You are right. – miguel-svq Jun 02 '14 at 01:59
0

window["some_string"] will make a global variable named some_string. like var some_string.

so replace

console.log($(item)[0]);

with

console.log(window[file.slice(0, -4)][0]);

it will make that string file.slice(0, -4), a global variable.

----OR----

var item = file.slice(0, -4);
item = window[item]; // make that string a global variable

then

console.log(item[0]);
Janaka R Rajapaksha
  • 3,585
  • 1
  • 25
  • 28