0

I have a multidimensional array named "notes". It has the fields "note1", "note2", and "note3".

I have a variable named "noteNum" that can be set to 1, 2, or 3.

If "noteNum = 2", then "notes[0].note + noteNum" should be equal to "notes[0].note2". BUT I can't seem to attach the variable? Why not?

My code is below:

// Array constructor
function notesConstructor(note1, note2, note3) {
    this.note1 = note1;
    this.note2 = note2;
    this.note3 = note3;
}

var notes = new Array();

notes[0] = new notesConstructor("Note 1A example note", "Note 2A example note", "Note 3A example note");
notes[1] = new notesConstructor("Note 1B example note", "Note 2B example note", "Note 3B example note");

console.log(notes[0].note1); // "Note 1A example note"

// WHERE THE PROBLEM IS...
var noteNum = 2;

console.log(notes[0].note + noteNum); // This SHOULD be "Note 2A example note" but it doesn't work

Fiddle: http://jsfiddle.net/baUaL/

user1822824
  • 2,478
  • 6
  • 41
  • 65
  • Bracket notation, `obj[prop]` – elclanrs Sep 22 '13 at 21:28
  • I get "TypeError: 'undefined' is not an object (evaluating 'notes[0].note[noteNum]')" – user1822824 Sep 22 '13 at 21:29
  • You're looking for `notes[0]["note"+noteNum]`. – Bergi Sep 22 '13 at 21:31
  • _“It has the fields "note1", "note2", and "note3"”_ – and why are those single variables, instead of being an array as well? Then you could easily access them via an index … Rule of thumb: Whenever you start using “numbering” in your variable names, you are doing it wrong. – CBroe Sep 22 '13 at 21:54
  • @CBroe, generalizing is ... generally wrong as well ;) Everything always depends on an implementation, especially if these names are fields representing some data. Though if numbers pile up and start having two digits, it's ... generally, starting to get messy. – Tomalla Sep 22 '13 at 22:53

2 Answers2

1

Try something like this:

console.log(notes[0]["note" + noteNum]);

As it is right now, you're trying to access field "note", which is undefined.

Tomalla
  • 567
  • 1
  • 6
  • 17
0

Try console.log( notes[0]["note"+noteNum] )

juuga
  • 1,274
  • 1
  • 13
  • 25