0

I am trying to do a little work in JavaScript and am new to the language, but not to program languages.

class Key{
    constructor(nm, keydata)    {
        var name = nm;
        var data = keydata;
    }
}

var KeySet = [];
for (i=0; i<5; i++){
    KeySet.push(new Key("item " +   i, "some data for " + i));
}

for (i=0; i<5; i++){
    console.log(i,KeySet[i].name," ->",KeySet[i].data)
}

I am getting this at the console:

0 undefined -> undefined 
1 undefined -> undefined 
2 undefined -> undefined 
3 undefined -> undefined 
4 undefined -> undefined
  1. Can I even build an array of objects?
  2. If so, what is wrong with the above? What is the best way?
  3. Do I have to do anything like cast the array item contents to a Key object to use it? How?

1 Answer 1

4

You're almost there! The result is undefined because the constructor declares the variables in its local scope, instead of defining those variables as instance variables.

To define instance variables, you need to bind those using this keyword. See the working example below:

class Key {
  constructor(nm, keydata) {
    this.name = nm;
    this.data = keydata;
  }
}

var KeySet = [];

for (i = 0; i < 5; i++) {
  KeySet.push(new Key("item " + i, "some data for " + i));
}

for (i = 0; i < 5; i++) {
  console.log(i, KeySet[i].name, " ->", KeySet[i].data)
}

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

3 Comments

Thank you. Isn't it almost always a head slapper? I am having issues with not having to declare every variable specifically.
By the way, do you have a favorite comprehensive source on the language?
@JohnHard -- for the second comment, I suggest you to regularly read MDN, and refer to its documentation for any help.

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.