zee
zee

Reputation: 359

select array by the value of variable using jQuery

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]
});

Upvotes: 0

Views: 1215

Answers (2)

miguel-svq
miguel-svq

Reputation: 2176

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.

Upvotes: 1

Janaka R Rajapaksha
Janaka R Rajapaksha

Reputation: 3764

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]);

Upvotes: 0

Related Questions