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

2 Answers 2

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.

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

3 Comments

mydata is not an array is an object. mydata=Array() seems unnecessary
javascript does not have associatve arrays as @Dalorzo pointed out. Answer is acheiving desired results but is not accurate regarding array vs object see: jsfiddle.net/aFMhx
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.
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]);

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.