0

I have a variable called "information" which creates a multi-dimensional array. For each row in the array, I want to return a variable whose name is the first value in the array. In other words, given the 'information' array below, I'd want the following output:

var lunalovegood = information[i][2] + ' ' + information[i][3] + ' is a ' + information[i]    [1] + '!'; //Luna Lovegood is a Ravenclaw!;
var dracomalfoy = information[i][2] + ' ' + information[i][3] + ' is a ' + information[i]    [1] + '!'; //Draco Malfoy is a Slythering!;;
var hermionegranger = information[i][2] + ' ' + information[i][3] + ' is a ' + information[i]    [1] + '!'; //Hermione Granger is a Gryffindor!;;

In other words, I want to be able to work with each of the elements in the 'information' array to create some markup. I already know how to get the information I need given the information array, but as you can see below I'd have to declare separate variables for each of the names.

for (var i = 0; i < information.length; i++) {
var htmlString = information[i][2] + ' ' + information[i][3] + ' is a ' + information[i]    [1] + '!'; //Luna Lovegood is a Ravenclaw!
$('div').html(htmlString);
} //end for loop 

var information = [
['lunalovegood', 'Ravenclaw', 'Luna', 'Lovegood', '(chaser)', 'lovegood.jpg', 4]
['dracomalfoy', 'Slytherin', 'Draco', 'Malfoy', '(seeker)', 'malfoy.jpg', 2],
['hermionegranger', 'Gryffindor', 'Hermione', 'Granger', '(none)', 'granger.jpg', 3],
];

The javascript below creates three variables called 'lunalovegood', 'dracomalfoy', and 'hermionegrange', but it's the long way of creating variables. How do I create these variables, one for each row in the array, by looping through the 0th indexed element in the 'information' array?

    var myVariables = {}
   ,varNames = ["lunalovegood","dracomalfoy","hermionegranger"]; 
for (var i=0;i<varNames.length;i+=1){

 myVariables[varNames[i]] = 0;
    console.log(lunalovegood);
}
1
  • You don't want variable names. Use an object (a key-value map) and its properties for the "names" Commented Oct 21, 2013 at 17:37

4 Answers 4

3

Your current approach just needs a most minor tweak to not require the second array.

var students = {}, i;
for (i = 0; i < information.length; ++i)
    students[information[i][0]] = information[i][2] + ' ' + information[i][3] + ' is a ' + information[i][1] + '!';

Now the key is set by taking the first item of the Array. You would then do the following for your text,

students['lunalovegood']; // "Luna Lovegood is a Ravenclaw!"

You're also missing a , in your information literal.

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

2 Comments

Hi -- thanks for responding. I'm a little confused -- does hermionegranger become a variable? Here's my JSFiddle using your answer: jsfiddle.net/YG5Lu/4
Oh wait, maybe i have to console.log students.hermionegranger instead of just hermionegranger... jsfiddle.net/YG5Lu/5
0

This should help you:

Every variable in the global scope can be accessed as a string property of the window object

var myvariable = 4;
alert(window["myvariable"]); // will alert 4

window["newvariable"] = 6;
alert(newvariable);   // will alert 6

2 Comments

I didn't ... this is just knowledge transfer
If one must have "variables", with is a slightly less blunt approach. (And it's actually used to great effect in something like Knockout.)
0

I agree with Bergi. Variables should represent a fixed finite set of members defined by code; data (as in the contents of a list) should generally not introduce new variables.

As such, here is the approach I would recommend (note that I've added a bit more than the "minimum required"; good luck!):

// Using a function makes it easy to change details and avoid leaking
// variables accidentally.
function loadWizards(information) {
  var wizards = [];
  for (var i = 0; i < information.length; i++) {
    var info = information[i];
    var name = info[0];
    // Mapping to named properties means we can forget about indices!
    wizards[name] = {     // <- use Name to map to our Wizard object
        house: info[1],
        // ..
        image: info[7]
    };            
  }
  return wizards;
}

// I have no idea if they are wizards, but give variables useful names.
// 'information' is too generic.
var wizards = loadWizards(information);

// Then later on, use it as:
alert("Hello " + wizards['hermionegranger'].name + "!")
                       // ^-- property access by Name

Comments

0
var formattedInfo = {}; 
$.each(information, function (i, v) {
    formattedInfo[v[0]] = v[2] + ' ' + v[3] + ' is a ' + v[1];
});

there is a missing comma at the end of the 1st line of your definition of information.

BTW, I like Harry Potter very much.

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.