JavaScript - cannot set property of undefined
In javascript almost everything is an object, null
and undefined
are exception.
Instances of Array
is an object. so you can set property of an array, for the same reason,you can't set property of a undefined, because its NOT an object
you never set d[a]
to any value.
Because of this, d[a]
evaluates to undefined
, and you can't set properties on undefined
.
If you add d[a] = {}
right after d = {}
things should work as expected.
Alternatively, you could use an object initializer:
d[a] = {
greetings: b,
data: c
};
Or you could set all the properties of d
in an anonymous function instance:
d = new function () {
this[a] = {
greetings: b,
data: c
};
};
If you're in an environment that supports ES2015 features, you can use computed property names:
d = {
[a]: {
greetings: b,
data: c
}
};
You have to set d[a]
to either an associative array, or an object:
d[a] = [];
d[a] = {};
Without setting, this is what's happening:
d[a] == undefined
, so you're doing undefined['greeting']=b;
and by definition, undefined has no properties. Thus, the error you received.
The object stored at d[a]
has not been set to anything. Thus, d[a]
evaluates to undefined
. You can't assign a property to undefined
:). You need to assign an object or array to d[a]
:
d[a] = [];
d[a]["greeting"] = b;
console.debug(d);