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
- Can I even build an array of objects?
- If so, what is wrong with the above? What is the best way?
- Do I have to do anything like cast the array item contents to a Key object to use it? How?
1 Answer 1
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)
}
answered Aug 7, 2018 at 3:06
31piy
23.9k6 gold badges51 silver badges69 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
John Hard
Thank you. Isn't it almost always a head slapper? I am having issues with not having to declare every variable specifically.
John Hard
By the way, do you have a favorite comprehensive source on the language?
lang-js